Skip to content

Commit fd79928

Browse files
physicsrobclaude
andcommitted
Typing: make mypy . green (410 -> 0)
Typing-only campaign: dynamic attributes declared on Node and HeadlessTransformer as bare class-body annotations; ortools CpModel calls migrated to the snake_case API the stubs declare (runtime aliases on 9.15, each verified before renaming; solver-side CamelCase kept where snake_case equivalents are properties); the rest is annotations, Optional corrections, and typing.cast. One type: ignore in the whole tree. make lint passes; full Modal suite green except the pre-existing staircase drift failure. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
1 parent f2de5a7 commit fd79928

41 files changed

Lines changed: 460 additions & 327 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

examples/calculator_advanced.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -294,7 +294,7 @@ def _make_compressor(embedding: Embedding):
294294
}
295295

296296
def compress(digits: List[Node]):
297-
values = [Linear(d, value_proj, name="digit_value") for d in digits]
297+
values: List[Node] = [Linear(d, value_proj, name="digit_value") for d in digits]
298298
total = sum_nodes(values) # plain-number add of up to 11 digits, 0..99
299299
bucket = bool_to_01(in_range(total, add_const(total, 1.0), n_buckets))
300300
sum_digit = onehot_lookup(bucket, sum_table, zero_digit)

examples/calculator_scratchpad.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@
7070
wrong-but-valid number.
7171
"""
7272

73-
from typing import Callable, Dict, List, Tuple
73+
from typing import Callable, Dict, List, Optional, Tuple, Union, cast
7474

7575
import torch
7676

@@ -580,7 +580,7 @@ def _emit_gathered_answer(
580580
col_onehot: Node,
581581
N: int,
582582
*,
583-
sign_at: Callable[[int], Node] = None,
583+
sign_at: Optional[Callable[[int], Node]] = None,
584584
) -> List[Node]:
585585
"""The trimmed, MSB-first answer, one slot per ``layout.n_answer``.
586586
@@ -624,7 +624,7 @@ def _emit_gathered_answer(
624624
match_gain=_MATCH_GAIN,
625625
)
626626
if t == 0 and sign_at is not None:
627-
answer.append(select(ge, picked, minus))
627+
answer.append(select(cast(Node, ge), picked, minus))
628628
else:
629629
answer.append(select(compare(idx, thresh=N - 0.5), eos, picked))
630630
return answer
@@ -767,6 +767,7 @@ def _sub_op(
767767
# constant-depth; here the recurrence rides the decode axis, where
768768
# serial is the point. ---
769769
combine_table: Dict[torch.Tensor, torch.Tensor] = {}
770+
nxt: Union[int, Node]
770771
for v in range(_CMP_W):
771772
for a in range(10):
772773
for b in range(10):

scripts/arithmetic_scaling.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ def critical_path_depth(outputs) -> int:
153153
Computed with an explicit stack (iterative post-order) so deep graphs do
154154
not overflow Python's recursion limit.
155155
"""
156-
memo = {}
156+
memo: dict = {}
157157
for root in outputs:
158158
stack = [(root, False)]
159159
while stack:

scripts/calculator_layer_table.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ def collect_cell(impl_name: str, n: int) -> dict:
135135
try:
136136
out, embedding = impl.create_network_parts(max_digits=n)
137137
except Exception as exc: # structural caps (slow planes, fact table)
138-
row = {"n": n, "build_error": str(exc).splitlines()[0]}
138+
row: dict = {"n": n, "build_error": str(exc).splitlines()[0]}
139139
if hasattr(impl, "n_params"):
140140
row["params_extrapolated"] = impl.n_params(n)
141141
if hasattr(impl, "compiled_layers"):

scripts/calculator_stats.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import json
2020
import os
2121
import tempfile
22+
from typing import cast
2223

2324
import torch
2425

@@ -63,7 +64,7 @@ def whole_calculator_stats() -> None:
6364
d_head=D_HEAD,
6465
verbose=False,
6566
)
66-
sidecar = json.load(open(artifact.debug_path))
67+
sidecar = json.load(open(cast(str, artifact.debug_path)))
6768

6869
peak = _peak_residual_occupancy(sidecar)
6970
print(f" layers : {artifact.n_layers}")

scripts/diagnose_calculator_layer_gap.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
import argparse
2525
import importlib
2626
from collections import Counter
27-
from typing import Dict, List, Tuple
27+
from typing import Any, Callable, Dict, List, Tuple, cast
2828

2929
from torchwright.compiler.lower import lower
3030
from torchwright.compiler.forward.cpsat_scheduler import (
@@ -57,13 +57,13 @@ def longest_chain(gm, es: Dict[int, int]) -> List:
5757
if u.node_id in preds and v.node_id in preds:
5858
preds[v.node_id].append(u.node_id)
5959

60-
cur = max(es, key=es.get)
60+
cur = max(es, key=cast(Callable[[int], int], es.get))
6161
chain = [cur]
6262
while True:
6363
candidates = [u for u in preds[cur] if es[u] >= es[cur] - 1]
6464
if not candidates:
6565
break
66-
cur = max(candidates, key=es.get)
66+
cur = max(candidates, key=cast(Callable[[int], int], es.get))
6767
chain.append(cur)
6868
return [by_id[i] for i in reversed(chain)]
6969

@@ -196,7 +196,7 @@ def main() -> None:
196196
print(f"[{args.impl} n={args.n}] nonlinear-op depth: {depth}")
197197

198198
if args.forensic:
199-
lowered = lower(
199+
lowered: Any = lower(
200200
out,
201201
collapse_univariate=True,
202202
collapse_pl=False,

scripts/ffn_equivalence.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
from __future__ import annotations
3030

3131
from dataclasses import dataclass, field
32-
from typing import Callable, Dict, List, Optional
32+
from typing import Any, Callable, Dict, List, Optional, cast
3333

3434
import torch
3535

@@ -151,7 +151,7 @@ def schedule_metrics(
151151
if output_node in computed:
152152
break
153153
attn_ops, mlp_ops, _biased = sched.schedule_layer(rmap, computed)
154-
heads = sum(_count_heads_by_type(attn_ops, d_head).values())
154+
heads = sum(_count_heads_by_type(cast(Any, attn_ops), d_head).values())
155155
per_layer_heads.append(heads)
156156
slots = sum(len(op.mlp_slots) for op in mlp_ops if op.mlp_slots)
157157
peak_hidden = max(peak_hidden, slots)
@@ -207,10 +207,10 @@ def schedule_trace(
207207
if op.op_type == "compute_ffn":
208208
composites.append(
209209
(
210-
op.node.annotation,
211-
op.node.d_output,
210+
cast(Node, op.node).annotation,
211+
cast(Node, op.node).d_output,
212212
len(op.mlp_slots),
213-
op.node.node_id,
213+
cast(Node, op.node).node_id,
214214
)
215215
)
216216
trace.append({"layer": i, "hidden": hidden, "composites": composites})

scripts/investigate_log_precision.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
import torch
1616

17-
from torchwright.ops.relu.arithmetic_ops import log
17+
from torchwright.ops.relu.arithmetic_ops import log # type: ignore[attr-defined]
1818
from torchwright.ops.inout_nodes import create_input
1919

2020

scripts/investigate_onehot_leak.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838

3939
import torchwright.ops.swiglu.map_select as _map_select
4040
import torchwright.ops.swiglu.onehot_table as _onehot_table
41+
from torchwright.graph import Node
4142
from torchwright.graph.node import suppress_checks
4243
from torchwright.ops._math import _lookup_numeric_slack
4344
from torchwright.ops.inout_nodes import create_input
@@ -76,7 +77,7 @@ def __exit__(self, *exc):
7677
return _Ctx()
7778

7879

79-
def build_carry_chain(scale_override: Optional[float]) -> Dict[str, object]:
80+
def build_carry_chain(scale_override: Optional[float]) -> Dict[str, Node]:
8081
"""total -> in_range(total, total+1, 61) -> bool_to_01 -> lookups.
8182
8283
The exact shape of calculator_simple.multiply_digit_seqs' carry sweep,
@@ -110,7 +111,7 @@ def build_carry_chain(scale_override: Optional[float]) -> Dict[str, object]:
110111
}
111112

112113

113-
def build_times_table(scale_override: Optional[float]) -> Dict[str, object]:
114+
def build_times_table(scale_override: Optional[float]) -> Dict[str, Node]:
114115
"""Two machine-built one-hot digits -> two-block times-table lookup.
115116
116117
The multi-block (swiglu-lane) path of onehot_lookup, fed by the same
@@ -141,7 +142,7 @@ def build_times_table(scale_override: Optional[float]) -> Dict[str, object]:
141142

142143

143144
def sweep_carry(
144-
nodes: Dict[str, object], deltas: List[float], device: torch.device
145+
nodes: Dict[str, Node], deltas: List[float], device: torch.device
145146
) -> Dict[str, torch.Tensor]:
146147
ts, dvals = [], []
147148
for t in range(N_SLOTS):
@@ -180,7 +181,7 @@ def sweep_carry(
180181

181182

182183
def sweep_times_table(
183-
nodes: Dict[str, object], deltas: List[float], device: torch.device
184+
nodes: Dict[str, Node], deltas: List[float], device: torch.device
184185
) -> Dict[str, torch.Tensor]:
185186
rows: List[Tuple[int, int, float]] = []
186187
for da in range(10):

scripts/measure_fusion_opportunities.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
4646
import importlib
4747
import json
4848
from collections import Counter
49-
from typing import Dict, List, Optional, Tuple
49+
from typing import Any, Dict, List, Optional, Tuple, cast
5050

5151
from torchwright.compiler.collapse import scalar_sources
5252
from torchwright.compiler.graph_clone import topological_order
@@ -170,7 +170,7 @@ def _subgraph_details(
170170
if s is not None and s is not n:
171171
by_src.setdefault(s, []).append(n)
172172

173-
reports = []
173+
reports: List[Dict[str, Any]] = []
174174
for s, members in by_src.items():
175175
mset = set(members)
176176
# Longest chain inside the subgraph, overall and critical-only.
@@ -271,7 +271,9 @@ def analyze(
271271
members = [n for n in order if src[n] is not None and src[n] is not n]
272272
lv2 = _collapsed_levels(order, src)
273273
depth2 = lv2[out]
274-
subgraph_sizes = Counter(src[n].name or type(src[n]).__name__ for n in members)
274+
subgraph_sizes = Counter(
275+
cast(Node, src[n]).name or type(src[n]).__name__ for n in members
276+
)
275277

276278
# Feasibility-filtered variant: a collapsed univariate subgraph is one
277279
# FFN whose breakpoint grid must resolve the composed function over
@@ -304,7 +306,7 @@ def _feasible(s: Node) -> bool:
304306
]
305307

306308
# Families 1+2 combined.
307-
lv12 = {}
309+
lv12: Dict[Node, int] = {}
308310
for n in order:
309311
s = src[n]
310312
if s is not None and s is not n:

0 commit comments

Comments
 (0)