HN 日本語サマリー

← 一覧へ戻る
プログラミング

PyTorch全体を1ページで

The whole of PyTorch on one page (tensor.khalilli.ai)

6 pointsby akhalilli0 コメント

要約

この記事は、PyTorchの内部構造を包括的に解説するシリーズの導入部です。Pythonからコンパイルされたコード、ディスパッチャー、カーネルに至るまで、8つの階層を高速に traverser します。特に、PythonとC++間の境界を越える際のオーバーヘッドや、ディスパッチャーが操作をどのようにルーティングするかについて説明し、PyTorchの複雑なアーキテクチャへの理解を深めるためのロードマップを提供します。

全文翻訳

マップ

Loss, Death, Robots, Part 0

  1. マップ(このパート)
  2. テンソル
  3. Autograd
  4. 日々の PyTorch
  5. PyTorch を見る
  6. 機械
  7. PyTorch の拡張
  8. コンパイラ
  9. カーネルとハードウェア
  10. 分散
  11. 出荷
  12. PyTorch で働く

PyTorch の全体像を1ページで。

2026年8月07日 36分

[画像: the Loss, Death, Robots robot: an orange robot head whose left eye is the PyTorch flame]

目次

[画像: a code panel with the three lines x equals torch dot randn, loss equals model of x dot sum, loss dot backward, and an orange arrow pointing down to the words eight floors below this code][画像: a code panel with the three lines x equals torch dot randn, loss equals model of x dot sum, loss dot backward, and an orange arrow pointing down to the words eight floors below this code]

図1. このシリーズ全体が扱うプログラム。

あなたはこのようなコードを何千回も書いたことでしょう。このシリーズは、そのコードのすべてを理解できるように存在します。Python で書かれた部分、C++ に到達する部分、記録されるグラフ、選択されるカーネル、使用されるメモリ、そしてそれらが実行される2つのクロック。それらの言葉のそれぞれに、下の階層で明確な意味が与えられます。

これはパート0、マップです。まず、すべての階層を一度、速く下っていきます。次に、領域を描きます。そして、残りのコードベースを予測可能にする12のアイデア。次に、このシリーズがどのように機能するか、そしてそれをどう読むか。ここでは何も完全には説明しません。すべてに場所が与えられ、完全な説明には番号付きのパートが待っています。

始める前に一つの約束があります。このシリーズで測定されるすべての数値は、あなたが自分で実行できる小さなスクリプトから来ており、数値が現れる場所にリンクされています。私はこれらの測定を、torch 2.11.0 を搭載した Apple M3 Max ラップトップで行いました
[1]。あなたの数値は異なるでしょう。しかし、それらが作るパターンは同じです。

The fall

PyTorch は深いです。あなたのキーボードとチップの間には8つのレベルがあります。私はそれらを「階層」と呼び、このメーターがそれらすべてを示します。シリーズ全体を通して戻ってくるので、あなたは常に自分がどの深さにいるかを知ることができます。

[画像: a vertical depth meter with eight floor marks labeled your code, python, the boundary, the dispatcher, the kernel, the allocator, the queue, the gpu, with an orange marker at the top floor][画像: a vertical depth meter with eight floor marks labeled your code, python, the boundary, the dispatcher, the kernel, the allocator, the queue, the gpu, with an orange marker at the top floor]

図2. 深さメーター。オレンジ色の点があなたの現在地を示します。

建物を学ぶ最速の方法は、一度立ち止まらずにすべてを下りてみることです。それがこのセクションです。

Floor one: python

torch.randn は Python 関数のように見えます。Python にそれが実際に何であるかを尋ねてみましょう。

>>> type(torch.randn)
<class 'builtin_function_or_method'>

Python は、コンパイルされたコードで書かれた関数にのみこの型を与えます。コンパイルされたコードとは、あなたがインストールする前にマシン命令に翻訳されたコードのことです。そのため、中に読み取れる Python の本体はなく、デバッガーが停止する行もありません。

では、そのマシン命令はどこに存在するのでしょうか?共有ライブラリの中にあります。共有ライブラリとは、プログラムが実行中にロードするコンパイル済みコードのファイルです。それらはディスク上の torch パッケージ内にあり、見ることができます(証明):

torch._C -> _C.cpython-312-darwin.so  (49 KB, ローダー)
libtorch_cpu.dylib        206.5 MB   (テンソルとカーネル)
libtorch_python.dylib      28.5 MB   (境界の Python 側)

p0_the_library.py 証明、読み取りまたは実行可能

"""Proof: where the compiled part of pytorch actually lives.

torch._C is a thin compiled stub; the weight of the framework is in
the shared libraries next to it. Prints the files and their sizes.
"""
import glob
import os
import torch

stub = torch._C.__file__
print(f"torch {torch.__version__}")
print(f"torch._C -> {os.path.basename(stub)}  "
      f"({os.path.getsize(stub)/1024:.0f} KB stub)")
libdir = os.path.join(os.path.dirname(stub), "lib")
for lib in ["libtorch_cpu.dylib", "libtorch_python.dylib"]:
    p = os.path.join(libdir, lib)
    if os.path.exists(p):
        print(f"{lib:24s} {os.path.getsize(p)/1024/1024:6.1f} MB")

ダウンロードして実行する

サイズを読み取って、それらを見てみましょう。

[画像: a dashed outline labeled your process after import torch contains two blocks drawn to scale by file size: a huge one for libtorch cpu at 206.5 megabytes and a thin one for libtorch python at 28.5 megabytes; a magnifier blows up a six-pixel orange dot into the 49 kilobyte loader; an orange arrow shows torch dot randn jumping straight into the big block; a small inset named your machine holds one process, tied to the large dashed box by a line labeled enlarged][画像: a dashed outline labeled your process after import torch contains two blocks drawn to scale by file size: a huge one for libtorch cpu at 206.5 megabytes and a thin one for libtorch python at 28.5 megabytes; a magnifier blows up a six-pixel orange dot into the 49 kilobyte loader; an orange arrow shows torch dot randn jumping straight into the big block; a small inset named your machine holds one process, tied to the large dashed box by a line labeled enlarged]

図3. ファイルサイズでスケールを描画。Python から見える PyTorch の部分はオレンジ色の点です。

Python から見える PyTorch の部分は 49 KB のファイルで、その唯一の仕事は他の2つをロードすることです。実際の本体は 235 MB のコンパイル済みコードです。import torch はそれをあなたのプロセスにロードし、その後 torch.randn を呼び出すことは、その本体にジャンプすることを意味します。今日はこれらのファイルが存在することだけを知っていれば十分です。

これはコードベースの最初の正直な驚きです。あなたが一日中書いている Python は、そのレイヤーの中で最も小さいものです。

The boundary

呼び出しはすぐに Python を離れます。どこに着地するのでしょうか?

前の階層の 28.5 MB のライブラリ内にある THPVariable_randn という名前の C++ 関数です。そして、覚えておくと良い奇妙な事実があります。この関数は PyTorch リポジトリには存在しません。リポジトリをクローンして名前を検索しても、何も見つかりません。プログラムがビルド中にこの関数と、その何千もの兄弟を書き出します。下のアイデア4がその理由を説明し、パート5がその書き込みを行うプログラムを示します。

[画像: two territories labeled python and c++ separated by a wall with one gate, an orange call arrow crossing through the gate into a box labeled THPVariable_randn][画像: two territories labeled python and c++ separated by a wall with one gate, an orange call arrow crossing through the gate into a box labeled THPVariable_randn]

図4. 2つの言語間の境界。すべてのテンソル操作がこれを横断します。

この境界を越えるには時間がかかります。そのコストだけを見るために、最小限の操作(ほとんど算術演算が隠れていないもの)の時間を計測してみましょう(証明):

add, 1 element   :    0.538 マイクロ秒/呼び出し
add, 4M elements :  337.264 マイクロ秒/呼び出し

p2_dispatch_cost.py 証明、読み取りまたは実行可能

"""Proof: the fixed cost of one eager op, and why size hides it.

Times the same `a + b` at two sizes. The one-element add is nearly
pure machinery (dispatch, wrapping, allocation); the 4M-element add is
nearly pure arithmetic. CPU, single process.
"""
import time
import torch

def per_op_us(a, b, iters):
    # warmup
    for _ in range(2000):
        a + b
    t0 = time.perf_counter()
    for _ in range(iters):
        a + b
    return (time.perf_counter() - t0) / iters * 1e6

tiny = per_op_us(torch.ones(1), torch.ones(1), 200_000)
big_n = 4_000_000
big = per_op_us(torch.ones(big_n), torch.ones(big_n), 2_000)

print(f"torch {torch.__version__}, cpu")
print(f"add, 1 element   : {tiny:8.3f} us/op")
print(f"add, 4M elements : {big:8.3f} us/op")
print(f"machinery share of the tiny op: ~all of it")
print(f"ops/sec you can issue from python: {1e6/tiny:,.0f}")

# The sweep behind the toll meter: the same add at twelve sizes,
# 1 to 4M elements in powers of four. Every dot on the widget's
# axis is one line of this output.
import json
sweep = []
for k in range(12):
    n = 4 ** k
    iters = max(1_000, min(200_000, 40_000_000 // max(n, 1)))
    us = per_op_us(torch.ones(n), torch.ones(n), iters)
    sweep.append({"n": n, "us": round(us, 3)})
    print(f"add, {n:>9,} elements : {us:9.3f} us/op")
print("JSON_SWEEP=" + json.dumps(sweep))

ダウンロードして実行する

1要素の加算はほとんど数学を行いません。そのため、0.54マイクロ秒はほぼ純粋な呼び出しコストです:Python を離れ、引数をチェックし、結果オブジェクトを構築し、返します。半マイクロ秒は取るに足らないように聞こえます。これは、Python が毎秒約190万操作しか発行できないことを意味し、単一のトレーニングステップには数千の操作が含まれます。この数値を覚えておいてください。アイデア6で再び登場します。

The dispatcher

境界の下で、呼び出しは PyTorch の最も奇妙なマシン、ディスパッチャーに到達します。ディスパッチャーは、各操作に対して、どのコード片がどの順序で実行されるかを決定するルーターです。

それが決定しなければならないことを見てみましょう。あなたの3行のコードは「勾配を記録せよ」とは一言も言っていません。あなたのコードに if 文はなく、それをオンにするものはありません。それにもかかわらず、どこかで、この行列乗算を backward() のために記憶する必要があると決定されました。その何かがディスパッチャーです。すべての操作は、固定されたレイヤーのスタックを下っていきます。各レイヤーは呼び出しに作用したり、変更したり、変更せずに通過させたりできます。勾配を計算する PyTorch の部分である Autograd は、そのようなレイヤーの1つです。混合精度も別のレイヤーです。今回の実行では、Autograd のみ稼働しています。

[画像: an orange call passes down through stacked layers labeled argument parsing, autograd, autocast, functionalization, cpu backend; the autograd layer is highlighted and a side box shows the node AddmmBackward0 written to the graph][画像: an orange call passes down through stacked layers labeled argument parsing, autograd, autocast, functionalization, cpu backend; the autograd layer is highlighted and a side box shows the node AddmmBackward0 written to the graph]

図5. 算術演算が始まる前に、4つのレイヤーがあなたの呼び出しに触れます。今日稼働しているのはハイライトされたレイヤーのみです。

The kernel

スタックの最下部で、1つの具体的な関数が選択されます。「選択された」という言葉が適切です。この torch のビルドには 3,677 の登録済み操作名があります(証明 はカウントを表示します)、そして名前は関数本体ではありません。addmm 操作、つまり model(x) の背後にある行列乗算には、CPU 用、各種類の GPU 用、各データ型用、密行列用、疎行列用で別々の本体があります。このような、1つのデバイスと1つのデータ型のために書かれた本体をカーネルと呼びます。ディスパッチャーの最後の仕事は、そのうちの1つを選択することです。

[画像: the name addmm points at a grid of cells: rows for cpu, cuda and mps, columns for float32, float16, bfloat16 and int8; each cell is a separate function body; the cpu float32 cell is highlighted as the one this run uses; a dashed copy of the grid behind it stands for sparse tensors][画像: the name addmm points at a grid of cells: rows for cpu, cuda and mps, columns for float32, float16, bfloat16 and int8; each cell is a separate function body; the cpu float32 cell is highlighted as the one this run uses; a dashed copy of the grid behind it stands for sparse tensors]

図6. 1つの名前、グリッド状の本体。ディスパッチャーは呼び出しごとに1つのセルを正確に選択します。

p4_micro_proofs.py 証明、読み取りまたは実行可能

"""Micro-proofs quoted in Part 0: storage sharing, view errors,
mutation rewriting history, the no_grad layer, float32 absorption."""
import torch

print(f"torch {torch.__version__}\n")

# 1. a tensor is a window over storage
x = torch.arange(6, dtype=torch.float32)
v = x.view(2, 3)
print("same bytes under both:", x.data_ptr() == v.data_ptr())
print("v.stride():", v.stride(), " v.t().stride():", v.t().stride())
try:
    v.t().view(-1)
except RuntimeError as e:
    print("v.t().view(-1) ->", str(e).split(".")[0])

# 2. mutation rewrites the recorded program
a = torch.ones(3, requires_grad=True)
y = a * 2
print("\nbefore add_:", type(y.grad_fn).__name__)
y.add_(1)
print("after  add_:", type(y.grad_fn).__name__)

# 3. no_grad removes one dispatcher layer
with torch.no_grad():
    z = a * 2
print("\ninside no_grad, grad_fn:", z.grad_fn)

# 4. float32 absorbs small numbers
t = torch.tensor(1e8)
print("\n(1e8 + 1) - 1e8 in float32 =", ((t + 1) - t).item())

# 5. the size of the operation list (idea 3)
print("\nregistered operation names:",
      len(torch._C._dispatch_get_all_op_names()))

ダウンロードして実行する

操作の完全なリストは、リポジトリの1つのファイルにあります:native_functions.yaml
[2]。その兄弟ファイルである derivatives.yaml
[3] は各操作の導関数をリストしています。それ以外のすべては、これら2つのファイルから成長します。リポジトリの他のどのファイルも、1行あたりの情報量でこれほど多くを教えてくれるものはありません。

[画像: a long list of operation names narrowing through a funnel into a chooser labeled device cpu dtype float32, which points to a single highlighted box labeled one kernel actually multiplying][画像: a long list of operation names narrowing through a funnel into a chooser labeled device cpu dtype float32, which points to a single highlighted box labeled one kernel actually multiplying]

図7. 左に3,677の名前。右に1つの関数本体。漏斗はディスパッチャーの最後の仕事です。

1階層下にはメモリがあります。torch.randn(64, 128) は 32,768 バイトを必要とします:64行 × 128列 × 4バイト/要素。CPU ではこれは通常のメモリ割り当てです。GPU ではそうではありません。そこでは、PyTorch は独自のメモリ割り当て器を実行します。これは、GPU ドライバーから一度に大きなブロックを要求し、それらを再利用するメモリの管理者です。なぜなら、毎回ドライバーに要求するのは遅いからです。このメモリ割り当て器が、メモリが不足したときと、そのエラーが何を意味するかを決定します。パート4でこれを調べます。

The two clocks

ここで物語は二つに分かれます。以下は、PyTorch における最も有用なパフォーマンスに関する事実です。

GPU では、あなたの Python コードは実際には作業を行いません。それは作業を要求し、その要求はすぐに返されます。GPU は独自のクロックで作業を行い、Python は続行します。私はこれをこのマシンの GPU で測定しました(証明):

50回の行列乗算を要求する時間 :   1.58 ms
実際に作業が完了するまでの時間     :  73.83 ms
Python が自由だった時間          :  72.25 ms  (98%)

p3_two_timelines.py 証明、読み取りまたは実行可能

"""Proof: the CPU runs ahead of the GPU.

Queues 50 large matmuls on the MPS device and measures two times:
how long Python took to *ask* for the work, and how long the work
actually took. The difference is the gap the chapter draws.
"""
import time
import torch

assert torch.backends.mps.is_available(), "needs an Apple-silicon GPU"
dev = torch.device("mps")

a = torch.randn(2048, 2048, device=dev)
b = torch.randn(2048, 2048, device=dev)
for _ in range(5):          # warmup
    (a @ b)
torch.mps.synchronize()

t0 = time.perf_counter()
for _ in range(50):
    c = a @ b
t_queue = time.perf_counter() - t0
torch.mps.synchronize()
t_done = time.perf_counter() - t0

print(f"torch {torch.__version__}, mps")
print(f"time to queue 50 matmuls : {t_queue*1e3:8.2f} ms")
print(f"time until work finished : {t_done*1e3:8.2f} ms")
print(f"python was free for      : {(t_done-t_queue)*1e3:8.2f} ms ({(t_done-t_queue)/t_done:.0%} of the wall time)")

# The three ways to read the loss, measured, for the two-clocks
# widget: never, once at the end, after every step.
import json
def run_mode(mode, iters=50):
    for _ in range(5): # warmup
        (a @ b)
    torch.mps.synchronize()
    t0 = time.perf_counter()
    t_free = 0.0
    for i in range(iters):
        c = a @ b
        if mode == "every":
            c[0, 0].item() # force synchronization
    t_q = time.perf_counter() - t0
    if mode == "once":
        c[0, 0].item() # force synchronization
    torch.mps.synchronize()
    total = time.perf_counter() - t0
    return {"mode": mode, "queue_ms": round(t_q * 1e3, 2),
            "total_ms": round(total * 1e3, 2),
            "free_ms": round((total - t_q) * 1e3, 2)}

modes = [run_mode(m) for m in ("never", "once", "every")]
for m in modes:
    print(f"read {m['mode']:>5}: total {m['total_ms']:8.2f} ms, "
          f"python busy {m['queue_ms']:8.2f} ms")
print("JSON_MODES=" + json.dumps(modes))

ダウンロードして実行する

[画像: two horizontal timelines: the cpu lane shows a small orange block for requesting then a long free stretch; the gpu lane below shows contiguous orange work blocks spanning 74 milliseconds][画像: two horizontal timelines: the cpu lane shows a small orange block for requesting then a long free stretch; the gpu lane below shows contiguous orange work blocks spanning 74 milliseconds]

図8. 2つのクロック、1つのプログラム。CPU は最初の2ミリ秒で全てを要求しました。GPU は完了するためにさらに72ミリ秒必要としました。

Python は50回の乗算すべてを2ミリ秒未満で要求し、その後 GPU が72ミリ秒かけて計算する間、自由な状態で待機しました。CPU ではこのような分割はありません。計算はあなたの行が返る前に発生します。どのアクセラレータでも、この分割がプログラムの通常の状態です。

これが、Eager PyTorch が十分に高速である理由です。Python は先行して実行し、GPU はそれを待つ必要がありません。また、単純なタイミングコードが間違った結果を出す理由であり、トレーニングループ内の単一の loss.item() がステップ全体を遅くする可能性がある理由でもあります。.item() は実際の数値が必要です。その数値は、GPU がまだ完了していない作業キューの最後にあり、Python は停止してキュー全体を待つ必要があります。

[画像: a code panel for python at the top right, its print of loss dot item held in a dashed waiting box; below it an open channel of six tickets named matmul, add, relu, matmul, add and sum, the newest joining under python, an orange dashed line tying the waiting print to the sum ticket; at the bottom left the gpu takes the oldest ticket first][画像: a code panel for python at the top right, its print of loss dot item held in a dashed waiting box; below it an open channel of six tickets named matmul, add, relu, matmul, add and sum, the newest joining under python, an orange dashed line tying the waiting print to the sum ticket; at the bottom left the gpu takes the oldest ticket first]

図9. 2つのクロック間のキュー。Python が要求した数値は最後のチケットなので、その前のすべてのチケットが最初に完了する必要があります。

パート4では、この正確な図の上に正直な測定方法を教えます。

The turn

3行目:loss.backward()。これまでのところ、この行がどのように機能するかを説明するものは何もありません。順伝播の計算は終わっています。PyTorch はどのようにして微分できることを知っているのでしょうか?

それは、順伝播が2番目のジョブを持っていたからです。操作がディスパッチャーの Autograd レイヤーを通過するたびに、小さな記録が書き込まれました:どの操作が実行され、どの記録されたステップがその入力を生成したか。記録が記録を指す構造はグラフを形成します。そして、ここでその言葉は常にこの記録された構造を正確に意味します。loss が存在する時点までに、そのグラフも存在しています(証明):

loss.grad_fn     = SumBackward0
SumBackward0
  AddmmBackward0
    AccumulateGrad

p1_graph_chain.py 証明、読み取りまたは実行可能

"""Proof: loss.backward() walks a graph that forward quietly recorded.

Builds the chapter's three-line program and prints the autograd graph
that exists before backward is ever called.
"""
import torch
import torch.nn as nn

torch.manual_seed(0)
model = nn.Sequential(nn.Linear(128, 256), nn.ReLU(), nn.Linear(256, 10))

x = torch.randn(64, 128)
loss = model(x).sum()

print(f"torch {torch.__version__}")
print(f"x.grad_fn        = {x.grad_fn}")
print(f"loss.grad_fn     = {type(loss.grad_fn).__name__}")

node, depth = loss.grad_fn, 0
while node is not None and depth < 10:
    print("  " * depth + type(node).__name__)
    nexts = [n for n, _ in node.next_functions if n is not None]
    node = nexts[0] if nexts else None
    depth += 1

ダウンロードして実行する

[画像: on the left a staircase descends through x times w, plus b, and dot sum, and each fall writes its own record into a tall box named the graph, every record pointing an arrow at the record that produced its inputs, with loss dot grad underscore fn entering from below as the handle; on the right an orange staircase climbs the same three records in reverse, and gradients arrive at the inputs through AccumulateGrad][画像: on the left a staircase descends through x times w, plus b, and dot sum, and each fall writes its own record into a tall box named the graph, every record pointing an arrow at the record that produced its inputs, with loss dot grad underscore fn entering from below as the handle; on the right an orange staircase climbs the same three records in reverse, and gradients arrive at the inputs through AccumulateGrad]

図10. 順伝播は下りながらグラフを書き込みます。逆伝播は、書き込まれたものを正確にたどり、それ以外は何もしません。

backward() は何も発明しません。それは損失から入力までグラフをたどり、記録された各導関数を実行し、結果を .grad に格納します。たどることは AccumulateGrad で終わります。これは格納を行う記録です。そして、それはどこからも始まりません。x.grad_fn は None です。なぜなら x は直接作成されたもので、計算されたものではないからです。

ここで1つの疑問があなたを悩ませるはずです。導関数には値が必要です。行列乗算の導関数には、乗算された行列が必要です。順伝播はすでに終わっています。導関数を書き出すと、その必要性が明らかになります。

[画像: the forward line y equals x at w with x as a blue tile and w as a warm tile; below a dashed line labeled forward is over, the two backward formulas: grad underscore w equals x transposed at g, and grad underscore x equals g at w transposed, with the same blue and warm tiles appearing inside them; dashed threads carry each tile across the line into its formula][画像: the forward line y equals x at w with x as a blue tile and w as a warm tile; below a dashed line labeled forward is over, the two backward formulas: grad underscore w equals x transposed at g, and grad underscore x equals g at w transposed, with the same blue and warm tiles appearing inside them; dashed threads carry each tile across the line into its formula]

図11. x @ w の導関数を書き出したもの。数式には x と w 自体が含まれています。順伝播が使用したものは何でも、逆伝播でも再び必要とされます。

では、それらはどこにあるのでしょうか?順伝播中に、記録の隣に保存されていました。

[画像: the three records chained downward, each with a shelf beside it: SumBackward0 has a slim dashed shelf saying nothing; AddmmBackward0 has a large orange shelf holding the blue x tile and the warm w tile from the previous figure, with times every layer of your model written beneath it; AccumulateGrad has a slim dashed nothing shelf; below, the law that the saved values are used once at backward and freed][画像: the three records chained downward, each with a shelf beside it: SumBackward0 has a slim dashed shelf saying nothing; AddmmBackward0 has a large orange shelf holding the blue x tile and the warm w tile from the previous figure, with times every layer of your model written beneath it; AccumulateGrad has a slim dashed nothing shelf; below, the law that the saved values are used once at backward and freed]

図12. 各記録が保持したもの。これがトレーニング実行のメモリが実際に行く場所です。

したがって、順伝播はトレーニングがどれだけのメモリを消費するかを静かに決定します。パート2では、正確な保存ルールを示します。パート4では、それがどのように起こるかを監視する方法を示します。そして、アクティベーションチェックポインティングという手法は、そのメモリを余分な計算と引き換えにしますが、パート2にはそれ専用の章があります。

このセクションから1つの文を持ち出してください:逆伝播は、順伝播が書いたものしかたどることができません。それは小さく聞こえます。パート9では、クラスター内のどの GPU が互いに通信する必要があるかを決定するルールになります。

それがすべての「fall」でした:名前、境界、レイヤーのスタック、選択されたカーネル、メモリの管理者、2つのクロック、そして逆方向にたどられるグラフ。それでは、領域を正式に見てみましょう。

The territory

PyTorch はレイヤーで構築されており、各レイヤーは隣接するものにのみ話しかけます。以下の各ボックスは、このシリーズの少なくとも1つのパートです。

[画像: a stacked map of pytorch: the ecosystem on top with the logos of transformers, lightning, vllm, deepspeed and trl, then deployment, distributed and compiler towers, then the python api, the highlighted dispatcher, the aten kernels, the c10 core, and hardware at the bottom, with an orange line running down the left edge marking the fall from the previous section][画像: a stacked map of pytorch: the ecosystem on top with the logos of transformers, lightning, vllm, deepspeed and trl, then deployment, distributed and compiler towers, then the python api, the highlighted dispatcher, the aten kernels, the c10 core, and hardware at the bottom, with an orange line running down the left edge marking the fall from the previous section]

図13. システム全体を1枚のシートに。左側のオレンジ色の線は、先ほど通ったパスです。

同じ領域を、リポジトリ内のフォルダとして見てみましょう。もしコードベースを開くことがあれば、これが迷子にならないための地図です。

[画像: the pytorch repository as two river banks: torch and the compiler folders on the python side; aten and the imported third party kernels on the c++ side; torch csrc as the one bridge over the water; below both banks one wide layer named c10 carries support columns from every building, and torchgen sits underneath, writing generated code at build time][画像: the pytorch repository as two river banks: torch and the compiler folders on the python side; aten and the imported third party kernels on the c++ side; torch csrc as the one bridge over the water; below both banks one wide layer named c10 carries support columns from every building, and torchgen sits underneath, writing generated code at build time]

図14. リポジトリを2つの川岸として。川は図4の境界です。torch/csrc/ が唯一の橋です。そして両岸は同じ地面、c10/、テンソルとストレージ自体が存在する場所に立っています。

この地図に関する3つの事実は、数週間を節約してくれます。第一に、torch/ はプレーンな Python であり、今日そのすべてのファイルを読み取ることができます。第二に、aten/ と c10/ は C++ であり、テンソル、カーネル、ディスパッチャーはそこにあり、torch/csrc/ は2つの言語を接続する唯一の橋です。第三に、torchgen/ は境界階層のプログラムであり、ビルド中にコードを書き出すものです。あなたが読むリポジトリは入力であり、あなたが実行するライブラリは出力です。だから、リポジトリで THPVariable_randn を検索しても何も見つからないのです。

[画像: an iceberg: a small tip above the waterline labeled the repo you clone, and a much larger mass below labeled the code that runs, written by torchgen at build time][画像: an iceberg: a small tip above the waterline labeled the repo you clone, and a much larger mass below labeled the code that runs, written by torchgen at build time]

図15. リポジトリは水面上の部分です。あなたのプロセスが実行するコードは、それ以下のより大きな部分です。

コアの上にエコシステムが座っています。それは無限に見えますが、単純な形をしています:各ライブラリは、特定の、名前を付けられる場所に PyTorch にアタッチします。アタッチメントの場所を知っていれば、エコシステムを知ることができます。

[画像: pytorch drawn as a core with four named ports: nn.Module, optim, distributed, and the op set; libraries on an inner ring attach directly to those ports, with vllm and sglang sharing one dot as the runtime replacers; trl and peft sit on an outer ring attached to transformers instead, showing they build on it rather than on pytorch][画像: pytorch drawn as a core with four named ports: nn.Module, optim, distributed, and the op set; libraries on an inner ring attach directly to those ports, with vllm and sglang sharing one dot as the runtime replacers; trl and peft sit on an outer ring attached to transformers instead, showing they build on it rather than on pytorch]

図16. すべての線は、ライブラリがアタッチする正確な場所を指しています。trl と peft は外側のリングにあります:それらは PyTorch ではなく、transformers の上に構築されています。

中心から外側に向かって図を読んでください。transformers は nn.Module クラスとしてモデルを構築するため、パート3を理解していれば、そのソースを読むことができます。deepspeed は分散エンジンを置き換えるため、その場所はパート9です。vllm と sglang はモデルの重みを保持し、その周りのランタイムを置き換えます。そして trl と peft は PyTorch に直接触れることはありません。それらは transformers の上に構築されています。

エコシステム全体は1つの表に収まります。2番目の列は、各ファミリーが PyTorch リポジトリのどこにアタッチするかを示しています。

アタッチ先PyTorch 側誰が何を保持し、何をもたらすか
nn.Moduletorch/nn/transformers, diffusers, timmモデルは Module です。PyTorch が実行します
トレーニングループtorch/autograd/ torch/optim/lightning, acceleratePyTorch はエンジンとして残り、それらがそれを駆動します
分散エンジンtorch/distributed/deepspeedエンジンを交換し、ZeRO をもたらします
Eager ランタイムtorch/nn/ torch/library.pyvllm, sglang, TensorRT-LLM重みを保持し、ランタイムを置き換えます。それぞれ独自のカーネルを持つ csrc/ を備えています
操作リストaten/ torch/library.pyflash-attention, torchvision opsリストに新しい名前を追加します
2つの階層を同時にtorch/autograd/ + transformersunslothtransformers を通してトレーニングし、独自の Triton カーネルをもたらします
重みのみなし。重みファイルTEI, llama.cpp, MLXPyTorch を離れ、重みを保持しました。llama.cpp はそれを GGUF に再エンコードします

表の2行は図に値します。最初の行は Eager ランタイム、サービングエンジンが置き換えるものです。

[画像: left, eager pytorch: three code lines send three orange arrows down through a dashed band named the boundary, the dispatcher, a toll each, landing on three kernels named matmul, relu and sum, with the note three trips, three tolls; right, a serving engine with scheduler, batching and paged kv inside plans once and launches one fused block of matmul plus relu plus sum; both sides stand on one wide slab named the shared ground: torch tensors, nn.Module, the kernels themselves][画像: left, eager pytorch: three code lines send three orange arrows down through a dashed band named the boundary, the dispatcher, a toll each, landing on three kernels named matmul, relu and sum, with the note three trips, three tolls; right, a serving engine with scheduler, batching and paged kv inside plans once and launches one fused block of matmul plus relu plus sum; both sides stand on one wide slab named the shared ground: torch tensors, nn.Module, the kernels themselves]

図17. 1つのモデルを実行する2つの方法。エンジンは中央のループを置き換えます。地面は共有されます。

2番目は Triton です。表全体に現れるカーネル言語です:PyTorch のコンパイラがそれを書き、ライブラリは独自のものを持ち込みます。

[画像: a central box named at triton dot jit, gpu code in python syntax, wrapped in a dashed ring named torch dot autograd dot Function, a hand-written backward; torch underscore inductor, the compiler, points in from the left, pytorch writes triton itself; a blue tensor tile points in from the top right, runs on torch tensors through data underscore ptr; an arrow leaves to a small list of matmul, relu and a warm ticket named yours, registered through torch slash library dot py, a new name on the list][画像: a central box named at triton dot jit, gpu code in python syntax, wrapped in a dashed ring named torch dot autograd dot Function, a hand-written backward; torch underscore inductor, the compiler, points in from the left, pytorch writes triton itself; a blue tensor tile points in from the top right, runs on torch tensors through data underscore ptr; an arrow leaves to a small list of matmul, relu and a warm ticket named yours, registered through torch slash library dot py, a new name on the list]

図18. Triton と PyTorch。コンパイラは Triton 自体を書き込みます。手書きのカーネルは PyTorch テンソル上で実行され、リストに追加されます。

表を下方向に読むと、PyTorch の残存が各行で減少します。最後の行は重みファイル以外何も保持しません。それがエコシステムの静かな法則です:重みはランタイムよりも長生きします。パート10では、これらのアタッチメントポイントを1つずつ見ていきます。

The twelve ideas

PyTorch の大部分は、数千の個別の決定ではありません。それは少数のアイデアのセットであり、どこにでも適用されます。これら12のアイデアは、コードベースの残りを読む前に予測可能にします。それぞれが後で完全な章またはパートとして登場します。それぞれが現在、実行可能な証拠を伴っています。小さな証拠は1つのスクリプトを共有しています(証明)。

1. A tensor is a window over storage

テンソルは数値を保持しません。それは、どこを見るかの説明を保持します:単一のフラットなメモリブロックへのポインタ、各次元のサイズ、およびストライド。ストライドとは、そのフラットブロック内で次の要素に到達するために移動する必要があるステップ数です。2つのテンソルは完全に異なって見え、同じバイトを読み取ることができます。

>>> x = torch.arange(6.); v = x.view(2, 3)
>>> x.data_ptr() == v.data_ptr()   # same address in memory
True
>>> v.stride(), v.t().stride()     # transpose swapped the strides
((3, 1), (1, 3))

転置はデータを移動しませんでした。それは説明の中の2つの数字を入れ替えました。一部の説明は書き出すのが不可能であり、それがまさに v.t().view(-1) がエラーを発生させる一方で reshape はサイレントにデータをコピーする理由です。パート1はこのパズルから始まり、それを完全に解決します。

2. Autograd records a program you never wrote

あなたのコードでは、y は1つの名前であり、あなたはそれを自由に上書きします。2行目は1行目が作成した値を破壊します。グラフはそれを許容できません。逆伝播には各ステップが必要です。そのため、Autograd は変更ごとに1つの記録を書き込み、記録は決して上書きされません。y が変化するにつれて記録がどのように変化するかを見てみましょう。

>>> a = torch.ones(3, requires_grad=True)
>>> y = a * 2
>>> type(y.grad_fn).__name__
'MulBackward0'
>>> y.add_(1)                      # change y in place
>>> type(y.grad_fn).__name__
'AddBackward0'
>>> y[0] = 9                       # overwrite one slot
>>> type(y.grad_fn).__name__
'CopySlices'

[画像: left, what your code sees: three code cards named y equals a times 2, y dot add underscore 1, and y bracket 0 equals 9; the first two are struck through because each line replaced the old value; right, what the graph kept: three records named MulBackward0, AddBackward0 and CopySlices, chained by upward arrows, with y dot grad underscore fn entering at the newest; a dashed thread ties each code line to its record][画像: left, what your code sees: three code cards named y equals a times 2, y dot add underscore 1, and y bracket 0 equals 9; the first two are struck through because each line replaced the old value; right, what the graph kept: three records named MulBackward0, AddBackward0 and CopySlices, chained by upward arrows, with y dot grad underscore fn entering at the newest; a dashed thread ties each code line to its record]

図19. あなたのコードは1つの値を保持し、過去を破壊します。グラフは各ステップを保持します:変更ごとに1つの記録、何も上書きされません。

3つのステートメント、3つの記録、1つのチェーン。y.grad_fn は常に最新の記録を保持し、各記録は前の記録を指しているため、履歴全体にアクセス可能です。その履歴が、あなたが書かなかったプログラムです。あらゆる種類のインプレース変更の下でそれを正確に保つメカニズムには深みがあり、パート2の最も優れた章の1つです。

3. One list of operations is the whole interface

[画像: a code panel with the lines h equals x at w, h equals relu of h, loss equals h dot sum; an orange arrow labeled becomes points to three tiles named matmul, relu and sum, marked as the list with 3,677 possible names; a bracket collects the three tiles and fans out to three boxes named cpu, cuda and quantized][画像: a code panel with the lines h equals x at w, h equals relu of h, loss equals h dot sum; an orange arrow labeled becomes points to three tiles named matmul, relu and sum, marked as the list with 3,677 possible names; a bracket collects the three tiles and fans out to three boxes named cpu, cuda and quantized]

図20. 左側のコードはデバイスに到達しません。リストだけが到達します。

3,677の登録済み名前は PyTorch の実際のインターフェースです。各バックエンドはそれらのいくつかを実装しています。コンパイラはそれらで構成されたプログラムを書き換えます:torch.compile はあなたのプログラムがなったリストを読み取り、より短いリストを返します。そこでは、行列乗算とそれに続く加算が1つの addmm に融合され、小さな要素ごとの操作のチェーンが1つの生成されたカーネルになります。エクスポート形式はそれらを保存します:torch.export はリストをディスクにグラフとして書き込みます。ONNX ファイルは、各名前を ONNX の語彙に翻訳した同じ考え方です。量子化はそれらを置き換えます:float32 の行列乗算は int8 の本体に置き換えられます。リスト上の同じ場所、異なる算術演算です。新しい PyTorch 技術に遭遇したときは、まず1つの質問をしてください:それは操作に何をするのか?その答えは通常、全体の設計を説明します。

4. PyTorch writes most of its own code

[画像: a file icon labeled native functions yaml with an arrow branching into python bindings, autograd records, dispatcher entries and type stubs][画像: a file icon labeled native functions yaml with an arrow branching into python bindings, autograd records, dispatcher entries and type stubs]

図21. 1つの YAML ファイルを入力として、ビルド時に数千の関数が出力されます。

native_functions.yaml はすべての操作を宣言します。derivatives.yaml はすべての導関数を宣言します。ビルド時に、torchgen/ は両方を読み取り、Python バインディング、Autograd レコードクラス、ディスパッチャーテーブルを書き込みます。これが、リポジトリで呼び出したばかりの関数を検索しても何も見つからない理由です。あなたはビルドの入力を検索しましたが、関数は出力にあります。PyTorch で働く人々は最初に YAML を読みます。パート5の後、あなたもそうなるでしょう。

5. Features are layers with a switch

[画像: an orange call arrow passes down through a stack of three layers labeled autograd awake, autocast asleep, vmap asleep, then reaches the kernel][画像: an orange call arrow passes down through a stack of three layers labeled autograd awake, autocast asleep, vmap asleep, then reaches the kernel]

図22. すべての機能は同じ操作ストリームを監視します。コンテキストマネージャーは1つのレイヤーをスリープさせます。

PyTorch の機能は、それぞれがディスパッチャーのレイヤーであり、同じ操作ストリームを監視しているため、きれいに組み合わされます。

>>> with torch.no_grad():
...     z = a * 2
>>> z.grad_fn is None              # nothing was recorded
True

no_grad は関数を編集しませんでした。それは操作を Autograd レイヤーを通過させるフラグを設定するため、何も記録されません。混合精度、トレーシング、vmap も同じように機能し、それらが互いに知ることなく組み合わせることができる理由です。パート5はこのフラグの下のメカニズムを開きます。

6. Every operation pays a fixed cost first

数学の前に、すべての単一操作で、呼び出しとルーティングの半マイクロ秒。それが境界階層での測定でした。正直に適用すると、この1つの数値が torch.compile が存在する理由、融合オプティマイザーが存在する理由、そして遅いモデルに関する最初の質問が「計算によって制限されているのか、それとも多くの小さな操作を発行するコストによって制限されているのか?」である理由を説明します。

7. Memory, not speed, is what kills training runs

[画像: an account book with columns borrowed and repaid at backward, rows for activations, workspace and parameters][画像: an account book with columns borrowed and repaid at backward, rows for activations, workspace and parameters]

図23. 順伝播はメモリを借ります。逆伝播はそれを返します。メモリ不足はトレーニング実行が失敗する最も一般的な方法です。

遅いプログラムはそれでも完了します。GPU メモリ不足のプログラムは CUDA out of memory でクラッシュします。これは PyTorch で最も一般的な失敗です。順伝播は逆伝播のために値を保存します(上記の「The turn」)。メモリ割り当て器はブロックを保持し再利用します。それらの間で、トレーニングできるモデルのサイズが決まります。このシリーズでは、パート4でメモリを第一級の主題として扱います。

8. Python is why it won, and what it costs

[画像: a castle labeled python inside a blue ring of water, with one bridge leading out to the words c++ speed][画像: a castle labeled python inside a blue ring of water, with one bridge leading out to the words c++ speed]

図24. 保護と代償は同じ絵です:すべてが1つの橋を渡らなければなりません。

PyTorch が勝利したのは、通常の Python で、通常のデバッガーやプリント文で書けるからです。代償は、アイデア6の境界コストであり、すべての操作で支払われます。フレームワークの歴史は、最初のものを維持しながら2番目のものを削減しようとする試みの連続です。TorchScript は Python を独自の言語に置き換えようとしました。現在はメンテナンスモードです
[4]。現在のコンパイラはあなたの Python の実行を監視し、可能なものを翻訳します。そしてそれは勝利しています。覚えておくべきパターン:PyTorch の内部では、Python に賭けることは常に負けでした。

9. Forward decides what backward must do

[画像: a forward chain of boxes x, mul, add, loss above a dashed line, with its orange reflection below running in the opposite direction through the backward records][画像: a forward chain of boxes x, mul, add, loss above a dashed line, with its orange reflection below running in the opposite direction through the backward records]

図25. 逆伝播は、順伝播が書いたグラフの反射です。

逆伝播は、順伝播が書いたものしかたどることができません。1台のマシンでは、これは詳細のように聞こえます。スケールが大きくなると、それは土地の法律になります:分散トレーニングでは、順伝播でテンソルが GPU に分割される方法は、逆伝播でどの GPU がデータを交換する必要があるかを決定します。1つのアイデアが、ラップトップからクラスターまで。それはパート9の背骨です。

10. Shared bytes plus in-place writes cause the hardest problems

[画像: one block of storage with three overlapping window frames over it and a single orange write striking a cell that two of the windows share][画像: one block of storage with three overlapping window frames over it and a single orange write striking a cell that two of the windows share]

図26. 3つのウィンドウ、1つのストレージ、1つの書き込み。プログラムを記録または書き換えるすべてのシステムがこれを処理する必要があります。

アイデア1により、多くのテンソルが同じバイトを読み取ることができます。アイデア2により、それらのバイトをインプレースで変更できます。それらを組み合わせます:1回の書き込みが複数のテンソルの意味を一度に変更する可能性があり、プログラムを記録する(Autograd、コンパイラ、エクスポート)システムはすべてそれに気づき、正確でなければなりません。PyTorch の一部が奇妙に複雑に見えるときは、共有バイトとインプレース書き込みの組み合わせがそれに何をするかを尋ねてください。それが通常答えです。

11. The code keeps its history

[画像: a cross section of ground with four labeled layers: dynamo and inductor on top, then torchscript, the caffe2 merge, and the original TH C code from 2016 at the bottom][画像: a cross section of ground with four labeled layers: dynamo and inductor on top, then torchscript, the caffe2 merge, and the original TH C code from 2016 at the bottom]

図27. 4つのシステム、4つの時代、1つのリポジトリ。古いレイヤーがまだ透けて見えます。

リポジトリには、すべての時代の遺物が含まれています:2016年のオリジナルの C コード、2018年の Caffe2 マージ、2019年の TorchScript、2023年以降成長しているコンパイラ地区。ファイルが奇妙に見える場合、その説明は通常歴史的です:古い何かが最初にそこにありました。パート5は、現在を説明する場所でこの歴史を語ります。

12. Floating point is a contract; read it

[画像: a document titled float32 the contract, with a highlighted clause reading 1e8 plus 1 minus 1e8 equals 0, signed by every model you train][画像: a document titled float32 the contract, with a highlighted clause reading 1e8 plus 1 minus 1e8 equals 0, signed by every model you train]

図28. 条件は公開されています。すべてのトレーニング実行がそれに署名します。

>>> t = torch.tensor(1e8)
>>> ((t + 1) - t).item()
0.0

float32 数値は約7桁の精度を持っています。そのため、1億に1を加えると何も変わりません
[5]。これはバグではなく、数値形式が約束通りに機能しているのです。トレーニングで使用される、より高速で精度の低いフォーマット、さらに一部の GPU カーネルが実行ごとに異なる順序で合計するという事実を組み合わせると、「なぜ実行ごとに損失が変わったのか」という質問には正確な答えがあります。パート4では、この契約を条項ごとに読みます。

How this series draws

あなたが今見たすべての静止画は実際の Excalidraw シーンであり、シーンファイルはシリーズと共に提供されます。あなたはどの描画でも開いて編集できます。操作できる4つの楽器は同じ言語に従い、それらの内部のすべての数値は証拠スクリプトから来ています。それらすべてが1つの視覚言語を話すため、パート2までには思考なしでそれらを読み取れるようになります。

[画像: a legend sheet: an orange arrow meaning the subject in motion, an ink rectangle meaning structure, a grey panel meaning context, a dashed line meaning implied or asleep, the depth meter, and the robot with a note that it appears at most once per part][画像: a legend sheet: an orange arrow meaning the subject in motion, an ink rectangle meaning structure, a grey panel meaning context, a dashed line meaning implied or asleep, the depth meter, and the robot with a note that it appears at most once per part]

図29. 全ての記法を1枚のシートに。一度学べば、シリーズ全体で有効です。

オレンジ色は常に主題、つまり動いている唯一のものをマークします。インクは構造です。グレーはコンテキストです。破線は記録済み、暗示的、またはスリープ状態を意味します。深さメーターは階層を示します。そしてロボットはパートごとに最大1回登場します。なぜなら、どこにでもいるマスコットは面白くなくなるからです。

How to read this

12パート。各パートはこれと同様の長い1ページです。そして、このシリーズには各パートの背後に1つの静かな目標があります:終わりまでに、あなたは小さな PyTorch を自分で構築できるほど機械をよく理解しているはずです。メカニズムを示すすべての描画、図の隣にあるすべての数式、そしてすべての証拠スクリプトは、その一部です。

PartWhat is behind the door
0. The Mapyou are here
1. Tensorstorage, strides, views, data types, broadcasting
2. Autogradthe graph, in-place writes, checkpointing, double backward
3. Daily PyTorchnn, optim, data loading, mixed precision, seen from inside
4. Seeing PyTorchthe profiler, memory, floating point, honest measurement
5. The Machinerythe dispatcher, aten, torchgen, the history
6. Extending PyTorchsubclasses, custom operations, new backends
7. The Compilerdynamo, aot autograd, inductor, dynamic shapes
8. Kernels & Hardwarethe gpu model, triton, cutlass, what fast means
9. Distributedcollectives, ddp, fsdp, dtensor, parallel training
10. Ship Itexport, quantization, executorch, the ecosystem
11. Working on PyTorchthe contributor's field guide

最初から最後まで読む必要はありません。3つの読書ラインがパートを横断して走っています。駅を通過するラインのように。

各パート内の各章は同じ7つのステップに従うため、リズムはすぐに慣れ親しんだものになります。

[画像: a tall page outline with seven stacked bands labeled the question, the model, the mechanism, the source, the proof, the payoff, the frontier, with the proof band highlighted in orange][画像: a tall page outline with seven stacked bands labeled the question, the model, the mechanism, the source, the proof, the payoff, the frontier, with the proof band highlighted in orange]

図30. 各章の7つのステップ。証拠のステップが背骨です:スクリプトなしでは主張できません。

そして、あなたが信頼しているものを知っておくべきなので、方法を平易に述べます。すべてのメカニズムの主張は、ソースコードに対してチェックされるか、スクリプトによって示される前に公開されます。スクリプトは場所にリンクされ、1つの torch バージョンに固定されています。PyTorch が移動して主張が古くなった場合、章は修正され、その修正はページに記録されます。内部構造に関するシリーズがドリフトを認められない場合、1年以内に間違ったものになります。

What you can now say

このリストに対して自分自身をテストしてください。一度読んだ後、自分の言葉で言えるはずです。

  • type(torch.randn) が何を返すか、そしてコンパイルされた本体がディスク上のどこに実際に存在するのか。
  • ディスパッチャーとは何か、そして no_grad が関数を編集せずに Autograd を停止する方法。
  • カーネルとは何か、そしてどれが実行されるかを何が決定するのか。
  • CPU と GPU が2つのクロックで実行される理由、そしてそれが単純なタイミングコードを誤らせる理由。
  • グラフとは何か、誰がそれを書き、なぜ逆伝播が順伝播が書き留めなかったことを決してできないのか。
  • そして12のアイデア、それぞれ1つの文で。

もしこれらのいずれかが曖昧なら、その階層に戻ってください。それぞれわずか1分です。それがこのページが役立つ理由です。

Try it yourself

5つの証拠スクリプトが演習です。それぞれについて:まず出力を予測し、次に実行し、次に違いを説明してください。

  1. p0_the_library.py: あなた自身の torch インストールにあるコンパイル済みライブラリのサイズは?
  2. p1_graph_chain.py: 2層モデルが実行された後、どのようなグラフが残りますか?
  3. p2_dispatch_cost.py: あなたのマシンでの操作あたりの固定コストは?
  4. p3_two_timelines.py: Python が要求を終えた後、GPU はどれくらいの時間作業を続けていますか?
  5. p4_micro_proofs.py: 12のアイデアを5つの小さな実験に圧縮。

Pick a door

パート1はテンソルです。それはアイデア1からのパズルで始まります。そしてあなたは今、自分の目でそのエラーを見ました。

>>> v.t().view(-1)
RuntimeError: view size is not compatible with input tensor's
size and stride ...
>>> v.t().reshape(-1)   # this one works. why?
tensor([0., 3., 1., 4., 2., 5.])

同じテンソル。同じ要求。1つの行は拒否し、もう1つはサイレントにデータをコピーします。それら2つの行の違いは、このシリーズの最初のパート全体です。

次の階層でお会いしましょう。

References

[1] Khalilli, five proof scripts, measured on an Apple M3 Max, torch 2.11.0, CPU and Apple GPU, 2026. Linked in place above; rerun them to check me.

[2] PyTorch source, native_functions.yaml, pinned to the v2.11.0 tag. https://github.com/pytorch/pytorch/blob/v2.11.0/aten/src/ATen/native/native_functions.yaml

[3] PyTorch source, derivatives.yaml, pinned to the v2.11.0 tag. https://github.com/pytorch/pytorch/blob/v2.11.0/tools/autograd/derivatives.yaml

[4] PyTorch documentation, TorchScript, which states it is in maintenance mode. https://docs.pytorch.org/docs/stable/jit.html

[5] IEEE, 754 single precision: 24 binary digits of precision, about 7 decimal digits.

このページの後で読むのに良い3つのもの:Edward Yang の PyTorch internals talk、これは C++ 側を詳細にマッピングしています。 PyTorch Developer Podcast、同じ著者による短いエピソード。そしてリポジトリ自身の CONTRIBUTING.md、これはメンテナーの言葉でフォルダレイアウトを説明しています。


‹Floating Point