changh95's picture
tt-model push auto_steer-p150 (container)
7d7fddc verified
Raw History Blame Contribute Delete
21.7 kB
# SPDX-License-Identifier: Apache-2.0
"""The device plan of a VisionPilot network: the ONNX graph up to ``spec.cut`` as a list of steps on feature maps.
Layout: a feature map of batch 1 is ``rows x channels`` (``[H*W, C]``, ttnn's flattened ``[1, 1, H*W, C]``), a
vector is ``[1, N]``. The planner walks the folded graph once and maps node patterns to steps:
- ``Conv`` (+ ``Sigmoid`` + ``Mul`` SiLU) -> ``conv`` with the activation fused; a ``Conv`` on ``[1, C, 1]`` (CTX's
Conv1d over one position: only the centre tap sees data) -> ``linear``;
- ``Sigmoid`` + ``Mul`` elsewhere -> ``act silu``; ``Add`` / ``Mul`` of two maps -> ``add`` / ``mul``;
- ``Split`` / ``Concat`` on channels -> ``slice`` / ``concat``; ``MaxPool`` -> ``maxpool``; ``Resize`` nearest x2 ->
``upsample``;
- CTX: ``ReduceMean`` over H, W -> ``mean`` (vector); ``Squeeze`` -> alias; ``Reshape`` of the expanded vector to
``[1, 1, h, w]`` -> ``vec_to_map``;
- C2PSA attention: ``Reshape [1, C, h, w] -> [1, heads, 2*dk + dv, h*w]``, ``Split`` on that axis, Q^T K, scale,
``Softmax``, ``V @ A^T``, ``Reshape`` back (and V reshaped for the depth-wise positional conv) -> one ``attention``
step with two outputs.
Anything else raises, so a graph the planner does not understand never runs half-mapped. The ops after ``cut`` run
on the host (``tail`` / ``run_tail``). A backend executes the steps: ``host/rows_numpy.py`` (the layout check on the
host) or ``tt/backend.py`` (ttnn on the p150).
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Sequence, Set, Tuple
import numpy as np
from .graph import Graph, Node, scalar
from .models import NetworkSpec
@dataclass
class Step:
kind: str
inputs: Tuple[str, ...]
outputs: Tuple[str, ...]
params: Dict[str, Any] = field(default_factory=dict)
nodes: Tuple[str, ...] = ()
index: int = -1
def __repr__(self) -> str:
p = {k: v for k, v in self.params.items() if not isinstance(v, np.ndarray)}
return f"Step#{self.index}({self.kind} {list(self.inputs)} -> {list(self.outputs)} {p})"
# tensor metadata: ("map", h, w, c) or ("vec", n)
Meta = Tuple
class PlanError(ValueError):
pass
class Plan:
"""Steps of the device part of one network, built once from the folded graph."""
def __init__(self, graph: Graph, spec: NetworkSpec):
self.graph = graph
self.spec = spec
self.body: Set[str] = graph.ancestors(spec.cut)
self.meta: Dict[str, Meta] = {}
self.steps: List[Step] = []
self.input_format = "nchw" # "s2d4" after stem.rewrite_stem
self._consumed: Set[str] = set()
for name in spec.inputs:
n_, c, h, w = graph.shape(name)
if n_ != 1 or c != 3:
raise PlanError(f"input {name}: expected [1, 3, H, W], got {graph.shape(name)}")
self.meta[name] = ("map", h, w, c)
for n in graph.nodes_named(self.body):
if n.name in self._consumed:
continue
self._plan_node(n)
for i, s in enumerate(self.steps):
s.index = i
for c in spec.cut:
if c not in self.meta or self.meta[c][0] != "map":
raise PlanError(f"cut tensor {c} is not a feature map of the plan")
covered = {nm for s in self.steps for nm in s.nodes}
missing = self.body - covered
if missing:
raise PlanError(f"nodes left out of the plan: {sorted(missing)[:10]}")
self.tail: List[Node] = [n for n in graph.nodes if n.name not in self.body]
# ------------------------------------------------------------------ helpers
def _users(self, t: str) -> List[Node]:
return [u for u in self.graph.users(t) if u.name in self.body]
def _emit(self, step_kind: str, inputs: Sequence[str], outputs: Sequence[str], nodes: Sequence[Node], **params):
for n in nodes:
self._consumed.add(n.name)
self.steps.append(Step(step_kind, tuple(inputs), tuple(outputs), params, tuple(n.name for n in nodes)))
def _silu_after(self, t: str) -> Optional[Tuple[Node, Node]]:
"""(Sigmoid, Mul) when ``t`` is used only by ``Mul(t, Sigmoid(t))``."""
us = self._users(t)
if len(us) != 2 or len(self.graph.users(t)) != 2:
return None
sig = [u for u in us if u.op == "Sigmoid"]
mul = [u for u in us if u.op == "Mul"]
if len(sig) != 1 or len(mul) != 1:
return None
s, m = sig[0], mul[0]
if sorted(m.inputs) != sorted([t, s.outputs[0]]) or self.graph.users(s.outputs[0]) != [m]:
return None
return s, m
def _map(self, t: str) -> Meta:
m = self.meta.get(t)
if m is None or m[0] != "map":
raise PlanError(f"{t}: expected a feature map, got {m}")
return m
# ------------------------------------------------------------------ patterns
def _plan_node(self, n: Node) -> None:
g = self.graph
op = n.op
if op == "Conv":
self._plan_conv(n)
elif op == "Sigmoid":
x = n.inputs[0]
us = self._users(n.outputs[0])
if (len(us) == 1 and us[0].op == "Mul" and sorted(us[0].inputs) == sorted([x, n.outputs[0]])
and len(g.users(n.outputs[0])) == 1):
self._emit("act", [x], [us[0].outputs[0]], [n, us[0]], kind="silu")
self.meta[us[0].outputs[0]] = self.meta[x]
else:
self._emit("act", [x], [n.outputs[0]], [n], kind="sigmoid")
self.meta[n.outputs[0]] = self.meta[x]
elif op in ("Add", "Mul"):
a, b = n.inputs
if g.is_const(a) or g.is_const(b):
raise PlanError(f"{n.name}: {op} with a constant is not planned on the device")
ma, mb = self._map(a), self._map(b)
if ma != mb:
raise PlanError(f"{n.name}: {op} of {ma} and {mb} (no broadcasting on the device)")
self._emit(op.lower(), [a, b], n.outputs, [n])
self.meta[n.outputs[0]] = ma
elif op == "Split":
self._plan_split(n)
elif op == "Concat":
if int(n.attr("axis")) != 1:
raise PlanError(f"{n.name}: concat on axis {n.attr('axis')}")
ms = [self._map(i) for i in n.inputs]
if len({m[1:3] for m in ms}) != 1:
raise PlanError(f"{n.name}: concat of maps of different sizes {ms}")
self._emit("concat", n.inputs, n.outputs, [n])
self.meta[n.outputs[0]] = ("map", ms[0][1], ms[0][2], sum(m[3] for m in ms))
elif op == "MaxPool":
_, h, w, c = self._map(n.inputs[0])
k = tuple(n.attr("kernel_shape"))
s = tuple(n.attr("strides", [1, 1]))
p = tuple(n.attr("pads", [0, 0, 0, 0]))
if n.attr("ceil_mode", 0) or any(d != 1 for d in n.attr("dilations", [1, 1])) or p[0] != p[2] or p[1] != p[3]:
raise PlanError(f"{n.name}: max pool {n.attrs}")
oh = (h + 2 * p[0] - k[0]) // s[0] + 1
ow = (w + 2 * p[1] - k[1]) // s[1] + 1
self._emit("maxpool", n.inputs[:1], n.outputs, [n], kernel=k, stride=s, padding=(p[0], p[1]))
self.meta[n.outputs[0]] = ("map", oh, ow, c)
elif op == "Resize":
self._plan_resize(n)
elif op == "ReduceMean":
_, h, w, c = self._map(n.inputs[0])
axes = [int(a) for a in (g.const(n.inputs[1]).reshape(-1) if len(n.inputs) > 1 and n.inputs[1]
else n.attr("axes"))]
if sorted(a % 4 for a in axes) != [2, 3] or not n.attr("keepdims", 1):
raise PlanError(f"{n.name}: mean over axes {axes}")
self._emit("mean", n.inputs[:1], n.outputs, [n])
self.meta[n.outputs[0]] = ("vec", c)
elif op == "Squeeze":
m = self.meta.get(n.inputs[0])
if m is None or m[0] != "vec":
raise PlanError(f"{n.name}: squeeze of {m}")
self._emit("alias", n.inputs[:1], n.outputs, [n])
self.meta[n.outputs[0]] = m
elif op == "Reshape":
self._plan_reshape(n)
else:
raise PlanError(f"{n.name}: op {op} is not planned on the device")
def _plan_conv(self, n: Node) -> None:
g = self.graph
x = n.inputs[0]
m = self.meta.get(x)
w = g.const(n.inputs[1]).astype(np.float32)
b = g.const(n.inputs[2]).astype(np.float32) if len(n.inputs) > 2 and n.inputs[2] else None
fused = self._silu_after(n.outputs[0])
act = "silu" if fused else None
out = fused[1].outputs[0] if fused else n.outputs[0]
nodes = [n] + (list(fused) if fused else [])
if m is not None and m[0] == "vec":
if w.ndim != 3:
raise PlanError(f"{n.name}: conv of a vector with a {w.ndim}-D kernel")
k = w.shape[2]
pads = n.attr("pads", [0, 0])
if g.shape(x)[-1] != 1 or int(n.attr("group", 1)) != 1 or pads[0] != pads[1] or k != 2 * pads[0] + 1:
raise PlanError(f"{n.name}: Conv1d over {g.shape(x)} with kernel {k}, pads {pads}")
self._emit("linear", [x], [out], nodes, weight=np.ascontiguousarray(w[:, :, pads[0]]), bias=b, act=act,
name=n.name)
self.meta[out] = ("vec", int(w.shape[0]))
return
_, h, wd, c = self._map(x)
if w.ndim != 4:
raise PlanError(f"{n.name}: {w.ndim}-D conv kernel on a map")
if n.attr("auto_pad", "NOTSET") not in ("NOTSET", ""):
raise PlanError(f"{n.name}: auto_pad")
sh, sw = (int(s) for s in n.attr("strides", [1, 1]))
pt, pl, pb, pr = (int(p) for p in n.attr("pads", [0, 0, 0, 0]))
if any(int(d) != 1 for d in n.attr("dilations", [1, 1])):
raise PlanError(f"{n.name}: dilation")
groups = int(n.attr("group", 1))
kh, kw = w.shape[2:]
oh = (h + pt + pb - kh) // sh + 1
ow = (wd + pl + pr - kw) // sw + 1
if w.shape[1] * groups != c:
raise PlanError(f"{n.name}: kernel {w.shape} x groups {groups} vs {c} input channels")
self._emit("conv", [x], [out], nodes, weight=w, bias=b, stride=(sh, sw), padding=(pt, pb, pl, pr),
groups=groups, act=act, name=n.name)
self.meta[out] = ("map", oh, ow, int(w.shape[0]))
def _plan_split(self, n: Node) -> None:
g = self.graph
axis = int(n.attr("axis", 0))
_, h, w, c = self._map(n.inputs[0])
if axis != 1:
raise PlanError(f"{n.name}: split on axis {axis} outside an attention block")
if len(n.inputs) > 1 and n.inputs[1]:
sizes = [int(s) for s in g.const(n.inputs[1]).reshape(-1)]
else:
k = int(n.attr("num_outputs", len(n.outputs)))
if c % k:
raise PlanError(f"{n.name}: {c} channels into {k} parts")
sizes = [c // k] * k
start = 0
for i, (o, s) in enumerate(zip(n.outputs, sizes)):
self._emit("slice", n.inputs[:1], [o], [n] if i == len(sizes) - 1 else [], begin=start, end=start + s)
self.meta[o] = ("map", h, w, s)
start += s
def _plan_resize(self, n: Node) -> None:
g = self.graph
_, h, w, c = self._map(n.inputs[0])
if n.attr("mode", "nearest") != "nearest":
raise PlanError(f"{n.name}: resize mode {n.attr('mode')}")
oshape = g.shape(n.outputs[0])
if oshape[0] != 1 or oshape[1] != c or oshape[2] % h or oshape[3] % w:
raise PlanError(f"{n.name}: resize {g.shape(n.inputs[0])} -> {oshape}")
sh, sw = oshape[2] // h, oshape[3] // w
# integer-factor nearest equals repeat for these index rules (checked, not assumed)
ctm = n.attr("coordinate_transformation_mode", "half_pixel")
mode = n.attr("nearest_mode", "round_prefer_floor")
from .host.onnx_numpy import _resize
probe = np.arange(h * w, dtype=np.float32).reshape(1, 1, h, w)
fake = Node(n.name, "Resize", n.inputs, n.outputs, {"mode": "nearest",
"coordinate_transformation_mode": ctm, "nearest_mode": mode})
got = _resize(fake, [probe, None, None, np.asarray([1, 1, oshape[2], oshape[3]])])[0]
if not np.array_equal(got, np.repeat(np.repeat(probe, sh, 2), sw, 3)):
raise PlanError(f"{n.name}: nearest resize ({ctm}, {mode}) is not a plain repeat")
self._emit("upsample", n.inputs[:1], n.outputs, [n], scale=(sh, sw))
self.meta[n.outputs[0]] = ("map", oshape[2], oshape[3], c)
def _plan_reshape(self, n: Node) -> None:
g = self.graph
x = n.inputs[0]
m = self.meta.get(x)
oshape = g.shape(n.outputs[0])
if m is not None and m[0] == "vec" and len(oshape) == 4 and oshape[:2] == (1, 1):
if oshape[2] * oshape[3] != m[1]:
raise PlanError(f"{n.name}: vector of {m[1]} to {oshape}")
self._emit("vec_to_map", [x], n.outputs, [n], h=oshape[2], w=oshape[3])
self.meta[n.outputs[0]] = ("map", oshape[2], oshape[3], 1)
return
if m is not None and m[0] == "map" and len(oshape) == 4 and oshape[0] == 1 and oshape[3] == m[1] * m[2]:
self._plan_attention(n)
return
raise PlanError(f"{n.name}: reshape {g.shape(x)} -> {oshape} is not planned on the device")
def _one_user(self, t: str, op: str) -> Node:
us = self.graph.users(t)
if len(us) != 1 or us[0].op != op or us[0].name not in self.body:
raise PlanError(f"attention pattern: {t} should feed one {op}, feeds {[(u.op, u.name) for u in us]}")
return us[0]
def _plan_attention(self, r1: Node) -> None:
g = self.graph
x = r1.inputs[0]
_, h, w, c = self._map(x)
_, heads, cq, hw = g.shape(r1.outputs[0])
if heads * cq != c:
raise PlanError(f"{r1.name}: {heads} heads x {cq} != {c} channels")
sp = self._one_user(r1.outputs[0], "Split")
if int(sp.attr("axis")) != 2 or len(sp.outputs) != 3:
raise PlanError(f"{sp.name}: attention split {sp.attrs}")
dk, dk2, dv = [int(s) for s in g.const(sp.inputs[1]).reshape(-1)]
if dk != dk2 or 2 * dk + dv != cq:
raise PlanError(f"{sp.name}: split sizes {dk, dk2, dv}")
q, k, v = sp.outputs
tq = self._one_user(q, "Transpose")
if list(tq.attr("perm")) != [0, 1, 3, 2]:
raise PlanError(f"{tq.name}: perm {tq.attr('perm')}")
mm1 = self._one_user(tq.outputs[0], "MatMul")
if mm1.inputs != [tq.outputs[0], k] or g.users(k) != [mm1]:
raise PlanError(f"{mm1.name}: expected Q^T @ K")
ms = self._one_user(mm1.outputs[0], "Mul")
sc = [i for i in ms.inputs if g.is_const(i)]
if len(sc) != 1:
raise PlanError(f"{ms.name}: expected a constant scale")
scale = scalar(g.const(sc[0]))
sm = self._one_user(ms.outputs[0], "Softmax")
if int(sm.attr("axis", -1)) not in (-1, 3):
raise PlanError(f"{sm.name}: softmax axis {sm.attr('axis')}")
ta = self._one_user(sm.outputs[0], "Transpose")
if list(ta.attr("perm")) != [0, 1, 3, 2]:
raise PlanError(f"{ta.name}: perm {ta.attr('perm')}")
mm2 = self._one_user(ta.outputs[0], "MatMul")
if mm2.inputs != [v, ta.outputs[0]]:
raise PlanError(f"{mm2.name}: expected V @ A^T")
r2 = self._one_user(mm2.outputs[0], "Reshape")
vus = g.users(v)
rv = [u for u in vus if u.op == "Reshape"]
if len(vus) != 2 or len(rv) != 1:
raise PlanError(f"attention: V should feed the output matmul and one reshape, feeds {vus}")
rv = rv[0]
for r in (r2, rv):
if g.shape(r.outputs[0]) != (1, heads * dv, h, w):
raise PlanError(f"{r.name}: reshape to {g.shape(r.outputs[0])}")
self._emit("attention", [x], [r2.outputs[0], rv.outputs[0]], [r1, sp, tq, mm1, ms, sm, ta, mm2, r2, rv],
heads=heads, dk=dk, dv=dv, scale=scale, h=h, w=w)
self.meta[r2.outputs[0]] = ("map", h, w, heads * dv)
self.meta[rv.outputs[0]] = ("map", h, w, heads * dv)
# ------------------------------------------------------------------ execution
def run(self, backend: Any, feeds: Dict[str, Any], *, hook: Any = None, steps: Optional[Sequence[Step]] = None,
outputs: Optional[Sequence[str]] = None) -> Dict[str, Any]:
"""Execute ``steps`` (default: all); ``feeds`` maps each network input (and any other tensor the steps
read, e.g. a state) to a backend value. Returns ``outputs`` (default: the cut tensors) as backend values.
``hook(step, outputs)`` sees every step's outputs before inputs are released."""
steps = self.steps if steps is None else list(steps)
outputs = list(self.spec.cut if outputs is None else outputs)
env: Dict[str, Any] = dict(feeds)
last_use: Dict[str, int] = {}
for k, s in enumerate(steps):
for i in s.inputs:
last_use[i] = k
keep = set(outputs) | set(feeds)
for k, s in enumerate(steps):
args = [env[i] for i in s.inputs]
outs = backend.step(s, args, [self.meta[i] for i in s.inputs])
if not isinstance(outs, (list, tuple)):
outs = [outs]
for o, v in zip(s.outputs, outs):
env[o] = v
if hook is not None:
hook(s, outs)
for i in s.inputs:
if last_use.get(i) == k and i not in keep and i not in s.outputs and i in env:
v = env.pop(i)
if not any(other is v for other in env.values()): # an alias still holds it
backend.release(v)
return {c: env[c] for c in outputs}
def branches(self) -> Optional[Dict[str, Any]]:
"""For a two-input network whose two input branches are the same computation (AutoDrive: one backbone on
frame t-1 and frame t): ``{"prev": steps, "curr": steps, "head": steps, "boundary": [(prev tensor, curr
tensor), ...]}`` (the branch tensors the head reads, paired by position), else None. The steps are this
plan's own (after any rewrite). With it, frame t's ``curr`` boundary tensors are frame t+1's ``prev``
ones, so a stream needs one branch per frame."""
if len(self.spec.inputs) != 2:
return None
dep: Dict[str, frozenset] = {i: frozenset([i]) for i in self.spec.inputs}
for s in self.steps:
d = frozenset().union(*(dep.get(i, frozenset()) for i in s.inputs))
for o in s.outputs:
dep[o] = d
prev_in, curr_in = self.spec.inputs # the ONNX input order: (image_prev, image_curr)
prev = [s for s in self.steps if dep[s.outputs[0]] == {prev_in}]
curr = [s for s in self.steps if dep[s.outputs[0]] == {curr_in}]
head = [s for s in self.steps if len(dep[s.outputs[0]]) == 2]
if len(prev) != len(curr) or len(prev) + len(curr) + len(head) != len(self.steps):
return None
pos_prev = {o: (k, j) for k, s in enumerate(prev) for j, o in enumerate(s.outputs)}
pos_curr = {o: (k, j) for k, s in enumerate(curr) for j, o in enumerate(s.outputs)}
pos_prev[prev_in] = pos_curr[curr_in] = (-1, 0)
for a, b in zip(prev, curr): # same computation, step by step
if a.kind != b.kind or len(a.inputs) != len(b.inputs):
return None
if [pos_prev.get(i) for i in a.inputs] != [pos_curr.get(i) for i in b.inputs]:
return None
for key in set(a.params) | set(b.params):
va, vb = a.params.get(key), b.params.get(key)
if key == "name":
continue
if isinstance(va, np.ndarray) or isinstance(vb, np.ndarray):
if va is None or vb is None or va.shape != vb.shape or not np.array_equal(va, vb):
return None
elif va != vb:
return None
boundary = []
for s in head:
for i in s.inputs:
if dep.get(i) == {prev_in}:
k, j = pos_prev[i]
pair = (i, curr[k].outputs[j])
if pair not in boundary:
boundary.append(pair)
for s in head: # the curr boundary tensors are its partners
for i in s.inputs:
if dep.get(i) == {curr_in} and i not in [b for _, b in boundary]:
return None
return {"prev": prev, "curr": curr, "head": head, "boundary": boundary}
def run_tail(self, cut_nchw: Dict[str, np.ndarray]) -> Dict[str, np.ndarray]:
"""The host ops after the cut (numpy, float32): the network outputs from the cut tensors (NCHW)."""
from .host import onnx_numpy
env = onnx_numpy.run(self.graph, {}, nodes=self.tail, env=cut_nchw)
return {o: env[o] for o in self.graph.outputs}
def summary(self) -> Dict[str, Any]:
kinds: Dict[str, int] = {}
for s in self.steps:
kinds[s.kind] = kinds.get(s.kind, 0) + 1
return {"steps": len(self.steps), "kinds": kinds, "body_nodes": len(self.body), "tail_nodes": len(self.tail),
"tail_ops": sorted({n.op for n in self.tail})}