deepvis
deepvis — wrap PyTorch & JAX networks; focus, monitor, unroll into math, edit, and visualize.
>>> import deepvis as dv
>>> dv.visualize(model, x) # the one call: wrap, run on x, show every layer, tensor and output
>>> net = dv.wrap(model) # or keep the wrapper to edit, trace, unroll … (net.show(x) to look)
>>> net = dv.open("model.onnx") # a saved file: .onnx .keras .pt2 .pt .safetensors .npz
1"""deepvis — wrap PyTorch & JAX networks; focus, monitor, unroll into math, edit, and visualize. 2 3>>> import deepvis as dv 4>>> dv.visualize(model, x) # the one call: wrap, run on x, show every layer, tensor and output 5>>> net = dv.wrap(model) # or keep the wrapper to edit, trace, unroll … (net.show(x) to look) 6>>> net = dv.open("model.onnx") # a saved file: .onnx .keras .pt2 .pt .safetensors .npz 7""" 8 9import os 10 11from . import theme 12from .core.graph import ModelGraph, Node, ParamInfo 13from .manipulate.edits import Edit, load_edits, save_edits 14from .manipulate.interventions import ( 15 Intervention, 16 ablate, 17 add_noise, 18 amplify, 19 clamp, 20 custom, 21 intervention, 22 mean_ablate, 23 patch, 24 replace, 25 steer, 26) 27from .manipulate.ops import register_op 28from .manipulate.params import ParamRef 29from .monitor.recorder import Monitor, Trace 30from .monitor.training import TrainingLog 31from .errors import DeepvisError, DeepvisWarning 32from .net import Net, NodeView, Selection, wrap 33from .files import open_file as open # noqa: A001 - dv.open(path), like the builtin but for model files 34from . import callbacks 35from . import integrations # dv.integrations.log_wandb / log_tensorboard 36from .callbacks import watch 37 38 39def _wrap_for_export(model, inputs, params=None, wrap_kw=None): 40 from . import errors as E 41 42 if isinstance(model, Net): 43 args = E.prepare_inputs(model.backend.model if model.framework == "torch" else model, inputs, model.framework) 44 return model, args 45 from .files import is_model_file 46 47 if is_model_file(model): # dv.visualize("model.onnx"): the file's own inputs when none are given 48 net = open(model, sample_input=inputs) 49 return net, net.sample_input or () 50 E.check_model(model) 51 if inputs is None: 52 E.prepare_inputs(model, None, "") # raises the explained InputError 53 net = wrap(model, params, sample_input=inputs, **(wrap_kw or {})) 54 return net, net.sample_input 55 56 57def _check_options(options: dict, where: str, live: bool = False) -> None: 58 import inspect 59 60 from . import errors as E 61 62 known = [p for p in inspect.signature(Net.export_html).parameters if p not in ("self", "path", "inputs")] 63 if live: 64 from .viz.server import LiveServer 65 66 known += [p for p in inspect.signature(LiveServer.__init__).parameters 67 if p not in ("self", "net", "args", "ui", "host") and p not in known] + ["views", "start", "port"] 68 for k in options: 69 if k not in known: 70 hint = E.suggest(k, known) 71 raise E.OptionError(f"{where}() got an unknown option {k!r}.", 72 (hint + " " if hint else "") + "Options: " + ", ".join(known) + ".") 73 74 75def export_html(model, inputs, path: str, params=None, wrap_kw: dict | None = None, **kw) -> str: 76 """One call from any model to a self-contained interactive HTML file. 77 78 >>> dv.export_html(torch_model, x, "model.html", title="My CNN", views=("graph", "volumes")) 79 >>> dv.export_html(flax_module, x, "model.html", params=variables) 80 """ 81 _check_options(kw, "export_html") 82 net, args = _wrap_for_export(model, inputs, params, wrap_kw) 83 return net.export_html(path, *args, **kw) 84 85 86CAPTURE_ENV = "DEEPVIS_CAPTURE" # when set, visualize() writes its page to this file (the VS Code extension) 87CAPTURE_LINES_ENV = "DEEPVIS_CAPTURE_LINES" # "FILE:FIRST-LAST": only the call written on those lines is captured 88CAPTURE_STOP_ENV = "DEEPVIS_CAPTURE_STOP" # stop the script once the page is written 89CAPTURE_OPTIONS_ENV = "DEEPVIS_CAPTURE_OPTIONS" # JSON options added to the captured call (e.g. {"compare": "ckpt.pt"}) 90 91 92def _capture_wanted() -> bool: 93 """Is this visualize() call the one being captured? (Without $DEEPVIS_CAPTURE_LINES, every call is.)""" 94 import sys 95 96 spec = os.environ.get(CAPTURE_LINES_ENV) 97 if not spec: 98 return True 99 file, _, span = spec.rpartition(":") 100 first, _, last = span.partition("-") 101 lo, hi = int(first), int(last or first) 102 f = sys._getframe(2) # the caller of visualize() 103 while f is not None: 104 if os.path.abspath(f.f_code.co_filename) == os.path.abspath(file): 105 return lo <= f.f_lineno <= hi 106 f = f.f_back 107 return False 108 109 110def visualize(model, inputs, params=None, *, path: str | None = None, open_browser: bool | None = None, 111 live: bool = False, wrap_kw: dict | None = None, **options) -> Net: 112 """The one call: wrap ``model``, run it on ``inputs`` and show the interactive page — the inputs, every 113 intermediate tensor, the outputs, each layer drawn from its own numbers. 114 115 model a torch module · a flax module (``params=variables``) · an nnx / equinox model · ``(apply_fn, params)`` 116 inputs what you would call the model with: one tensor, or a tuple of them (``model(*inputs)``) 117 options anything :meth:`Net.export_html` takes — ``title``, ``start`` (the tab to open), ``views``, 118 ``tokenizer``, ``labels``, ``diffusion``, ``grads``, ``loss_fn``, ``sample``, ``depth`` … 119 120 The page goes to the file named by ``$DEEPVIS_CAPTURE`` (the VS Code extension), else to ``path``, else inline 121 in Jupyter, else your browser. Returns the wrapped :class:`Net` (``net.page`` is the file written, if any), so 122 you can keep going: ``net.equation()``, ``net.trace(x)``, ``net["fc1"].prune(0.5)`` … 123 124 ``live=True`` serves the page from this process instead, and returns the 125 :class:`~deepvis.viz.server.LiveServer`: call ``srv.update(step, loss=...)`` from a training loop and the page 126 follows along, or pass ``train_step=fn`` for Train / Pause / Step buttons (see :meth:`Net.serve`). Run from VS 127 Code with the deepvis extension, the live page opens beside the code. 128 """ 129 _check_options(options, "visualize", live=live) 130 if live: 131 net, args = _wrap_for_export(model, inputs, params, wrap_kw) 132 from .viz.server import LiveServer 133 134 srv = LiveServer(net, args, **options) 135 return srv.start(open_browser=True if open_browser is None else open_browser) 136 capture = os.environ.get(CAPTURE_ENV) 137 if capture and path and os.path.abspath(path) == os.path.abspath(capture): 138 capture = None # deepvis's own capture call: it handles the page itself 139 if capture and not _capture_wanted(): 140 if not path: 141 return _wrap_for_export(model, inputs, params, wrap_kw)[0] # another call is being captured: no page 142 capture = None 143 net, args = _wrap_for_export(model, inputs, params, wrap_kw) 144 target = capture or path 145 if capture and os.environ.get(CAPTURE_OPTIONS_ENV): 146 import json 147 148 options = {**options, **json.loads(os.environ[CAPTURE_OPTIONS_ENV])} 149 _check_options(options, "visualize") 150 if target: 151 net.page = net.export_html(target, *args, **options) 152 if capture and os.environ.get(CAPTURE_STOP_ENV): 153 from .errors import Captured 154 155 raise Captured(net.page) # the page is all that was asked for: skip the rest of the script 156 return net 157 from .viz.html.dashboard import Dashboard, in_notebook 158 159 d = Dashboard(net, args, **options) 160 if in_notebook() and not open_browser: 161 from IPython.display import display 162 163 display(d) 164 net.page = None 165 else: 166 d.display(open_browser=True) 167 net.page = d.path 168 return net 169 170 171def compare(model_a, model_b, inputs, params=None, *, names=("A", "B"), **options) -> Net: 172 """Two versions of one network side by side: ``model_b`` is another model, a state_dict or a checkpoint path 173 (.pt / .pth / .safetensors). The page opens on the Compare tab — how far each layer's weights and activations 174 moved, both outputs — and has every other view of ``model_a``. Options as :func:`visualize`.""" 175 options.setdefault("start", "compare") 176 return visualize(model_a, inputs, params, compare=model_b, compare_names=list(names), **options) 177 178 179def export_svg(model, inputs, path: str, params=None, wrap_kw: dict | None = None, **kw) -> str: 180 """One call from any model to a static SVG (or .html) architecture figure with expressive glyphs.""" 181 net, args = _wrap_for_export(model, inputs, params, wrap_kw) 182 return net.export_svg(path, *args, **kw) 183 184 185def equation_rule(kind): 186 """Register a custom LaTeX rule for a layer kind / class: see :mod:`deepvis.equations.rules`.""" 187 from .equations.rules import equation_rule as _er 188 189 return _er(kind) 190 191 192def scope(name: str): 193 """Name a region of a pure-JAX function so it shows up as one node (alias of ``jax.named_scope``).""" 194 import jax 195 196 return jax.named_scope(name) 197 198 199__all__ = [ 200 "visualize", "compare", "wrap", "open", "watch", "callbacks", "integrations", "export_html", "export_svg", "DeepvisError", "DeepvisWarning", "Net", "NodeView", "Selection", "ParamRef", "Monitor", "Trace", "TrainingLog", "ModelGraph", "Node", "ParamInfo", 201 "Edit", "load_edits", "save_edits", "register_op", "equation_rule", "scope", "theme", 202 "Intervention", "ablate", "mean_ablate", "amplify", "clamp", "steer", "add_noise", "replace", "custom", 203 "intervention", "patch", 204] 205__version__ = "0.1.0"
111def visualize(model, inputs, params=None, *, path: str | None = None, open_browser: bool | None = None, 112 live: bool = False, wrap_kw: dict | None = None, **options) -> Net: 113 """The one call: wrap ``model``, run it on ``inputs`` and show the interactive page — the inputs, every 114 intermediate tensor, the outputs, each layer drawn from its own numbers. 115 116 model a torch module · a flax module (``params=variables``) · an nnx / equinox model · ``(apply_fn, params)`` 117 inputs what you would call the model with: one tensor, or a tuple of them (``model(*inputs)``) 118 options anything :meth:`Net.export_html` takes — ``title``, ``start`` (the tab to open), ``views``, 119 ``tokenizer``, ``labels``, ``diffusion``, ``grads``, ``loss_fn``, ``sample``, ``depth`` … 120 121 The page goes to the file named by ``$DEEPVIS_CAPTURE`` (the VS Code extension), else to ``path``, else inline 122 in Jupyter, else your browser. Returns the wrapped :class:`Net` (``net.page`` is the file written, if any), so 123 you can keep going: ``net.equation()``, ``net.trace(x)``, ``net["fc1"].prune(0.5)`` … 124 125 ``live=True`` serves the page from this process instead, and returns the 126 :class:`~deepvis.viz.server.LiveServer`: call ``srv.update(step, loss=...)`` from a training loop and the page 127 follows along, or pass ``train_step=fn`` for Train / Pause / Step buttons (see :meth:`Net.serve`). Run from VS 128 Code with the deepvis extension, the live page opens beside the code. 129 """ 130 _check_options(options, "visualize", live=live) 131 if live: 132 net, args = _wrap_for_export(model, inputs, params, wrap_kw) 133 from .viz.server import LiveServer 134 135 srv = LiveServer(net, args, **options) 136 return srv.start(open_browser=True if open_browser is None else open_browser) 137 capture = os.environ.get(CAPTURE_ENV) 138 if capture and path and os.path.abspath(path) == os.path.abspath(capture): 139 capture = None # deepvis's own capture call: it handles the page itself 140 if capture and not _capture_wanted(): 141 if not path: 142 return _wrap_for_export(model, inputs, params, wrap_kw)[0] # another call is being captured: no page 143 capture = None 144 net, args = _wrap_for_export(model, inputs, params, wrap_kw) 145 target = capture or path 146 if capture and os.environ.get(CAPTURE_OPTIONS_ENV): 147 import json 148 149 options = {**options, **json.loads(os.environ[CAPTURE_OPTIONS_ENV])} 150 _check_options(options, "visualize") 151 if target: 152 net.page = net.export_html(target, *args, **options) 153 if capture and os.environ.get(CAPTURE_STOP_ENV): 154 from .errors import Captured 155 156 raise Captured(net.page) # the page is all that was asked for: skip the rest of the script 157 return net 158 from .viz.html.dashboard import Dashboard, in_notebook 159 160 d = Dashboard(net, args, **options) 161 if in_notebook() and not open_browser: 162 from IPython.display import display 163 164 display(d) 165 net.page = None 166 else: 167 d.display(open_browser=True) 168 net.page = d.path 169 return net
The one call: wrap model, run it on inputs and show the interactive page — the inputs, every
intermediate tensor, the outputs, each layer drawn from its own numbers.
model a torch module · a flax module (params=variables) · an nnx / equinox model · (apply_fn, params)
inputs what you would call the model with: one tensor, or a tuple of them (model(*inputs))
options anything Net.export_html() takes — title, start (the tab to open), views,
tokenizer, labels, diffusion, grads, loss_fn, sample, depth …
The page goes to the file named by $DEEPVIS_CAPTURE (the VS Code extension), else to path, else inline
in Jupyter, else your browser. Returns the wrapped Net (net.page is the file written, if any), so
you can keep going: net.equation(), net.trace(x), net["fc1"].prune(0.5) …
live=True serves the page from this process instead, and returns the
~deepvis.viz.server.LiveServer: call srv.update(step, loss=...) from a training loop and the page
follows along, or pass train_step=fn for Train / Pause / Step buttons (see Net.serve()). Run from VS
Code with the deepvis extension, the live page opens beside the code.
172def compare(model_a, model_b, inputs, params=None, *, names=("A", "B"), **options) -> Net: 173 """Two versions of one network side by side: ``model_b`` is another model, a state_dict or a checkpoint path 174 (.pt / .pth / .safetensors). The page opens on the Compare tab — how far each layer's weights and activations 175 moved, both outputs — and has every other view of ``model_a``. Options as :func:`visualize`.""" 176 options.setdefault("start", "compare") 177 return visualize(model_a, inputs, params, compare=model_b, compare_names=list(names), **options)
Two versions of one network side by side: model_b is another model, a state_dict or a checkpoint path
(.pt / .pth / .safetensors). The page opens on the Compare tab — how far each layer's weights and activations
moved, both outputs — and has every other view of model_a. Options as visualize().
727def wrap(model, params=None, *, sample_input=None, name: str | None = None, framework: str | None = None, 728 **kw) -> Net: 729 """Wrap a network. 730 731 * ``wrap(torch_module)`` 732 * ``wrap(flax_linen_module, variables, sample_input=x)`` 733 * ``wrap(nnx_module, sample_input=x)`` 734 * ``wrap(equinox_module, sample_input=x)`` 735 * ``wrap(apply_fn, params, sample_input=x)`` — any ``apply_fn(params, *inputs)``; ``wrap((apply_fn, params))`` 736 and ``wrap((linen_module, variables))`` work too 737 * ``wrap(keras_model, sample_input=x)`` — Keras 3, on the JAX, PyTorch or TensorFlow backend 738 * ``wrap("model.onnx")`` — an ONNX file (or ``onnx.ModelProto``), run in onnxruntime 739 """ 740 from . import errors as E 741 742 if params is None and isinstance(model, tuple) and len(model) == 2 and callable(model[0]): 743 model, params = model 744 if isinstance(model, (str, os.PathLike)) and str(model).lower().endswith(".onnx"): 745 framework = framework or "onnx" # an ONNX file: its path is the model 746 else: 747 from .files import is_model_file, open_file 748 749 if is_model_file(model): # .keras / .pt2 / .safetensors …: dv.open knows how to read it 750 return open_file(model, sample_input=sample_input, name=name) 751 E.check_model(model) 752 if type(model).__name__ == "ExportedProgram" and type(model).__module__.startswith("torch.export"): 753 from .backends.torch_backend import from_exported 754 755 model, example = from_exported(model) # torch.export: its module tree, classes and example inputs 756 if sample_input is None: 757 sample_input = example 758 name = name or "exported" 759 fw = framework or _detect(model, params) 760 if sample_input is not None and fw != "unknown": 761 sample_input = E.prepare_inputs(model, sample_input, fw) 762 if fw == "torch": 763 from .backends.torch_backend import TorchBackend 764 765 backend = TorchBackend(model, name=name, sample_input=sample_input, **kw) 766 elif fw == "flax": 767 from .backends.jax.flax_linen import LinenBackend 768 769 if params is None: 770 raise E.ModelError("a flax.linen module has no weights of its own; deepvis needs its variables.", 771 "pass them: dv.visualize(module, x, params=variables), where " 772 "variables = module.init(jax.random.PRNGKey(0), x).") 773 backend = LinenBackend(model, params, sample_input=sample_input, name=name, **kw) 774 elif fw == "nnx": 775 from .backends.jax.flax_nnx import NNXBackend 776 777 backend = NNXBackend(model, sample_input=sample_input, name=name, **kw) 778 elif fw == "equinox": 779 from .backends.jax.equinox_backend import EquinoxBackend 780 781 backend = EquinoxBackend(model, sample_input=sample_input, name=name, **kw) 782 elif fw == "keras": 783 from .backends.keras_backend import KerasBackend 784 785 backend = KerasBackend(model, sample_input=sample_input, name=name) 786 elif fw == "onnx": 787 from .backends.onnx_backend import OnnxBackend 788 789 backend = OnnxBackend(model, name=name, sample_input=sample_input) 790 if sample_input is None: # an ONNX model declares its inputs: make some, so the page has data 791 sample_input = backend._sample = backend.example_inputs() 792 elif fw == "jax": 793 from .backends.jax.pure import PureBackend 794 795 if params is None: 796 raise E.ModelError("a plain function needs its parameters to be wrapped.", 797 "pass them: dv.visualize((apply_fn, params), x) — apply_fn(params, x) must run.") 798 backend = PureBackend(model, params, sample_input=sample_input, name=name, **kw) 799 else: 800 raise E.unknown_model(model) 801 try: 802 net = Net(backend, sample_input) 803 if sample_input is not None: 804 net.graph # noqa: B018 - build eagerly so shapes are known 805 except E.DeepvisError: 806 raise 807 except Exception as exc: # noqa: BLE001 - attribute the failure: the model's, or deepvis's tracing 808 if sample_input is None: 809 raise 810 failed = E.probe(model, sample_input, fw) 811 if failed is not None: 812 raise E.run_error(failed, sample_input) from failed 813 if fw != "torch": 814 raise E.run_error(exc, sample_input) from exc 815 raise E.trace_error(exc) from exc 816 return net
Wrap a network.
wrap(torch_module)wrap(flax_linen_module, variables, sample_input=x)wrap(nnx_module, sample_input=x)wrap(equinox_module, sample_input=x)wrap(apply_fn, params, sample_input=x)— anyapply_fn(params, *inputs);wrap((apply_fn, params))andwrap((linen_module, variables))work toowrap(keras_model, sample_input=x)— Keras 3, on the JAX, PyTorch or TensorFlow backendwrap("model.onnx")— an ONNX file (oronnx.ModelProto), run in onnxruntime
32def open_file(path: str | os.PathLike, sample_input=None, *, trusted: bool = False, name: str | None = None): 33 """Open a saved model or weights file (see the module docstring for the formats).""" 34 from .net import Net, wrap 35 36 path = os.fspath(path) 37 if not os.path.exists(path): 38 raise ModelError(f"no such file: {path}", "check the path (relative paths start from the current directory).") 39 low = path.lower() 40 stem = name or os.path.splitext(os.path.basename(path))[0] 41 if low.endswith(".onnx"): 42 return wrap(path, sample_input=sample_input, name=stem) 43 if low.endswith((".keras", ".h5", ".hdf5")): 44 keras = _keras() 45 model = keras.models.load_model(path, compile=False) 46 if sample_input is None: 47 from .backends.keras_backend import example_inputs 48 49 sample_input = example_inputs(model) 50 return wrap(model, sample_input=sample_input, name=stem) 51 if low.endswith(".pt2"): 52 import torch 53 54 return wrap(torch.export.load(path), sample_input=sample_input, name=stem) 55 if low.endswith(".safetensors"): 56 from .backends.weights_backend import from_safetensors 57 58 return Net(from_safetensors(path)) 59 if low.endswith(".npz"): 60 import numpy as np 61 62 from .backends.weights_backend import WeightsBackend 63 64 with np.load(path, allow_pickle=False) as z: 65 arrays = {k: z[k] for k in z.files} 66 return Net(WeightsBackend(arrays, name=stem, source=path)) 67 if low.endswith((".pt", ".pth", ".bin", ".ckpt")): 68 return _open_torch(path, sample_input, trusted, stem) 69 raise ModelError(f"deepvis doesn't know the file type of {path!r}.", 70 f"it opens {', '.join(EXTENSIONS)}; or build the model in code and use dv.wrap(model).")
Open a saved model or weights file (see the module docstring for the formats).
63def watch(model, inputs, params=None, *, every: int | None = 50, **options) -> Watch: 64 """Open a live page for ``model`` on ``inputs`` (a sample batch) and return a :class:`Watch`: call 65 ``w.step(step, loss=...)`` from the training loop. ``every``: snapshot the layers every N steps. Other options 66 are :func:`deepvis.visualize`'s (``title``, ``labels``, ``tokenizer``, ``min_interval``, ``port`` …).""" 67 return Watch(model, inputs, params, every=every, **options)
Open a live page for model on inputs (a sample batch) and return a Watch: call
w.step(step, loss=...) from the training loop. every: snapshot the layers every N steps. Other options
are deepvis.visualize()'s (title, labels, tokenizer, min_interval, port …).
76def export_html(model, inputs, path: str, params=None, wrap_kw: dict | None = None, **kw) -> str: 77 """One call from any model to a self-contained interactive HTML file. 78 79 >>> dv.export_html(torch_model, x, "model.html", title="My CNN", views=("graph", "volumes")) 80 >>> dv.export_html(flax_module, x, "model.html", params=variables) 81 """ 82 _check_options(kw, "export_html") 83 net, args = _wrap_for_export(model, inputs, params, wrap_kw) 84 return net.export_html(path, *args, **kw)
One call from any model to a self-contained interactive HTML file.
>>> dv.export_html(torch_model, x, "model.html", title="My CNN", views=("graph", "volumes"))
>>> dv.export_html(flax_module, x, "model.html", params=variables)
180def export_svg(model, inputs, path: str, params=None, wrap_kw: dict | None = None, **kw) -> str: 181 """One call from any model to a static SVG (or .html) architecture figure with expressive glyphs.""" 182 net, args = _wrap_for_export(model, inputs, params, wrap_kw) 183 return net.export_svg(path, *args, **kw)
One call from any model to a static SVG (or .html) architecture figure with expressive glyphs.
22class DeepvisError(Exception): 23 """A problem deepvis can explain.""" 24 25 def __init__(self, what: str, fix: str | None = None): 26 self.what, self.fix = what, fix 27 super().__init__(f"{what}" + (f"\n → fix: {fix}" if fix else ""))
A problem deepvis can explain.
59class DeepvisWarning(UserWarning): 60 """Something was skipped or adjusted; the page is still made."""
Something was skipped or adjusted; the page is still made.
38class Net: 39 """A wrapped PyTorch / JAX network. 40 41 Build with :func:`deepvis.wrap`. Highlights:: 42 43 net.summary() # module tree 44 net["encoder.block2"] # focus on a sub-network (NodeView) 45 net["fc1.weight"][:, 3] = 0 # arbitrary weight surgery (undoable) 46 net.select("layers.*.fc*", kind="Linear").prune(0.3) 47 tr = net.trace(x) # every intermediate activation 48 with net.monitor("relu*") as mon: net(x) # persistent stats 49 with net.intervene("relu1", dv.ablate([2])): net(x) 50 net.equation(mode="expanded") # unroll into math 51 net.show(x) # interactive 3b1b-style dashboard 52 net.animate("forward", x, path="fwd.mp4") # manim video 53 """ 54 55 def __init__(self, backend: Backend, sample_input: Any = None): 56 self.backend = backend 57 self.history = History(self) 58 self._monitors: list[Monitor] = [] 59 self._sample = None if sample_input is None else ( 60 sample_input if isinstance(sample_input, tuple) else (sample_input,)) 61 self._last_args: tuple | None = None 62 self._version = 0 63 self.tokenizer = None # optional: token strings / next-token predictions in pages (see export_html) 64 self.labels = None # optional: class names for the output 65 self.page: str | None = None # the file dv.visualize() wrote 66 67 # --------------------------------------------------------------- basics 68 @property 69 def framework(self) -> str: 70 return self.backend.framework 71 72 @property 73 def name(self) -> str: 74 return self.backend.name 75 76 @property 77 def graph(self) -> ModelGraph: 78 if self.backend._graph is None: 79 if self._sample is not None: 80 self.backend.build_graph(*self._sample) 81 else: 82 self.backend.build_graph() 83 return self.backend._graph 84 85 def rebuild_graph(self, *inputs) -> ModelGraph: 86 """Re-trace the graph (e.g. with a new sample input to fill in shapes).""" 87 args = _as_args(inputs, self) if inputs else self._sample 88 if args: 89 self._sample = args 90 return self.backend.build_graph(*(args or ())) 91 92 def __call__(self, *args, **kwargs): 93 if len(args) == 1: 94 from . import errors as E 95 96 if E._is_mapping(args[0]): # net(tokenizer_output): bound to the forward's arguments by name 97 args = _as_args(args, self) 98 self._last_args = args 99 if self._sample is None and args: 100 self._sample = args 101 return self.backend.forward(*args, **kwargs) 102 103 @property 104 def sample_input(self) -> tuple | None: 105 return self._last_args or self._sample 106 107 def _invalidate(self) -> None: 108 self._version += 1 109 110 def export(self): 111 """The (edited) model in native form: torch Module, (module, variables), eqx/nnx model, or params.""" 112 return self.backend.export() 113 114 def load(self, native) -> "Net": 115 """Load new weights in native form, e.g. after an optimizer step in a JAX training loop. 116 117 Accepts what :meth:`export` returns: flax ``variables`` (or ``params``), an nnx / equinox model, a params 118 pytree, or a torch ``state_dict`` / module. Not recorded as an edit. 119 """ 120 self.backend.load(native) 121 self._invalidate() 122 return self 123 124 def clone(self) -> "Net": 125 """Independent copy (weights copied); history is not carried over.""" 126 return Net(self.backend.clone(), self._sample) 127 128 # ------------------------------------------------------------ navigation 129 def __getitem__(self, key: str): 130 path, idx = split_index(key) 131 params = self.backend.param_paths() 132 if path in params: 133 return ParamRef(self, path, idx) 134 g = self.graph 135 if path in g.nodes and idx is None: 136 return NodeView(self, path) 137 if is_pattern(path): 138 return self.select(path) 139 close = difflib.get_close_matches(path, list(g.nodes) + params, n=5) 140 raise KeyError(f"{key!r} is neither a node nor a parameter. Did you mean: {close}?") 141 142 def __setitem__(self, key: str, value) -> None: 143 if isinstance(value, (ParamRef, NodeView, Selection)): 144 return # result of an in-place operator (e.g. net["w"] *= 2) — already applied 145 target = self[key] 146 if not isinstance(target, ParamRef): 147 raise TypeError("assignment is supported on parameters (e.g. net['fc1.weight'][:, 0] = 0)") 148 target.set(value) 149 150 def __contains__(self, key: str) -> bool: 151 return key in self.graph.nodes or key in self.backend.param_paths() 152 153 def focus(self, path: str) -> "NodeView": 154 return NodeView(self, path) 155 156 @property 157 def root(self) -> "NodeView": 158 return NodeView(self, "") 159 160 def params(self, pattern: str | None = None) -> dict[str, ParamRef]: 161 paths = self.backend.param_paths() 162 if pattern: 163 paths = filter_paths(pattern, paths) 164 return {p: ParamRef(self, p) for p in paths} 165 166 def select(self, pattern: str | Iterable[str] | None = None, kind: str | Iterable[str] | None = None, 167 where: Callable[[Node], bool] | None = None, leaves: bool = True) -> "Selection": 168 """Select nodes by path glob/regex, canonical kind and/or predicate.""" 169 g = self.graph 170 kinds = {kind} if isinstance(kind, str) else set(kind) if kind else None 171 pats = [pattern] if isinstance(pattern, str) else list(pattern) if pattern else None 172 ids = [] 173 for n in g.nodes.values(): 174 if leaves and not n.is_compute: 175 continue 176 if n.op in ("input", "output") and pats is None: 177 continue 178 if pats and not any(match(p, n.id) for p in pats): 179 continue 180 if kinds and n.kind not in kinds and n.type_name not in kinds: 181 continue 182 if where and not where(n): 183 continue 184 ids.append(n.id) 185 return Selection(self, ids) 186 187 def _resolve_nodes(self, targets) -> list[str]: 188 if isinstance(targets, (NodeView,)): 189 return [targets.path] 190 if isinstance(targets, Selection): 191 return list(targets.ids) 192 if isinstance(targets, str): 193 targets = [targets] 194 g = self.graph 195 out = [] 196 for t in targets: 197 if isinstance(t, NodeView): 198 out.append(t.path) 199 elif t in g.nodes: 200 out.append(t) 201 else: 202 m = [n for n in filter_paths(t, list(g.nodes)) if g.nodes[n].is_compute] 203 if not m: 204 close = difflib.get_close_matches(t, list(g.nodes), n=5) 205 raise KeyError(f"no node matches {t!r}. Did you mean: {close}?") 206 out.extend(m) 207 return list(dict.fromkeys(out)) 208 209 def summary(self, show: bool = True) -> str: 210 """The network in one plain sentence, then a table of its layers, shapes and parameter counts.""" 211 from .viz.explain import describe 212 213 s = describe(self.graph, batched=self.framework != "equinox") + "\n" + self.graph.summary() 214 if show: 215 print(s) 216 return s 217 218 def num_params(self, trainable_only: bool = True) -> int: 219 """Parameter count; ``trainable_only=False`` also counts buffers (e.g. BatchNorm running statistics).""" 220 infos = (self.backend.param_info(p) for p in self.backend.param_paths()) 221 return sum(int(np.prod(i.shape)) for i in infos if i.trainable or not trainable_only) 222 223 def __repr__(self) -> str: 224 return (f"deepvis.Net({self.name}, framework={self.framework}, params={self.num_params():,}, " 225 f"edits={len(self.history)})") 226 227 def _repr_html_(self) -> str | None: 228 """Jupyter: evaluating ``net`` shows its expressive architecture figure (``net.show(x)`` is interactive).""" 229 import base64 230 from html import escape 231 232 cached = getattr(self, "_repr_cache", None) 233 if cached and cached[0] == self._version: 234 return cached[1] 235 try: 236 from .viz.diagram import diagram_svg 237 238 args = self.sample_input 239 svg = diagram_svg(self, args if args else None) 240 except Exception: # noqa: BLE001 - fall back to the text repr 241 return None 242 # an <img> keeps the figure's CSS from leaking into the notebook 243 b64 = base64.b64encode(svg.encode("utf-8")).decode("ascii") 244 out = (f'<div style="max-height:640px;overflow:auto;border:1px solid #333;border-radius:8px;background:#000">' 245 f'<img alt="{escape(self.name)} architecture" src="data:image/svg+xml;base64,{b64}" ' 246 f'style="display:block;max-width:none"></div>' 247 f'<div style="font:12px monospace;color:#888;margin-top:4px">{escape(repr(self))} · ' 248 f'net.show(x) opens the interactive dashboard</div>') 249 self._repr_cache = (self._version, out) 250 return out 251 252 # ----------------------------------------------------------- manipulation 253 def apply_edit(self, edit: Edit | dict) -> "Net": 254 """Apply one edit (recorded for undo/redo).""" 255 if isinstance(edit, dict): 256 edit = Edit.from_dict(edit) 257 new = compute_edit(self, edit) 258 before = {p: self.backend.get_param(p) for p in new} 259 for p, v in new.items(): 260 self.backend.set_param(p, v) 261 self.history.record(edit, before, {p: v.copy() for p, v in new.items()}) 262 self._invalidate() 263 return self 264 265 def apply_edits(self, edits) -> "Net": 266 """Apply a list of edits / dicts, or a JSON file / string of them (see ``net.history.export()``).""" 267 for e in load_edits(edits): 268 self.apply_edit(e) 269 return self 270 271 def edit(self, target: str, op: str | Callable, where=None, index=None, params=None, **args) -> "Net": 272 """``net.edit("fc1.weight", "scale", factor=2)`` or ``net.edit("fc*", lambda w: w.clip(-1, 1))``.""" 273 if callable(op): 274 args = {"fn": op} 275 op = "apply" 276 path, idx = split_index(target) 277 return self.apply_edit(Edit(op, path, index=index if index is not None else idx, args=args, 278 where=where, params=params)) 279 280 @contextlib.contextmanager 281 def edits(self): 282 """Temporary edits: everything applied inside the block is undone on exit.""" 283 start = self.history.pos 284 try: 285 yield self 286 finally: 287 self.history.undo(self.history.pos - start) 288 del self.history.entries[start:] 289 290 def undo(self, n: int = 1): 291 return self.history.undo(n) 292 293 def redo(self, n: int = 1): 294 return self.history.redo(n) 295 296 def reset(self) -> None: 297 """Restore all edited parameters to their original values.""" 298 self.history.reset() 299 300 def snapshot(self, label: str = "") -> Snapshot: 301 return Snapshot({p: self.backend.get_param(p) for p in self.backend.param_paths()}, label) 302 303 def restore(self, snap: Snapshot) -> "Net": 304 changed = {p: v for p, v in snap.values.items() if not np.array_equal(self.backend.get_param(p), v)} 305 if changed: 306 self.apply_edit(Edit("load", list(changed), args={"values": changed}, 307 label=f"restore snapshot {snap.label}".strip())) 308 return self 309 310 def diff(self, reference: Snapshot | None = None, show: bool = True) -> list[dict]: 311 rows = diff(self, reference) 312 if show: 313 print(format_diff(rows)) 314 return rows 315 316 def permute_neurons(self, node: str, perm) -> "Net": 317 """Permute a layer's output neurons and its consumers' inputs (function-preserving).""" 318 return self.apply_edit(Edit("permute_neurons", node, args={"perm": np.asarray(perm).tolist()})) 319 320 def interpolate(self, other: "Net", alpha: float = 0.5, select: str = "**") -> "Net": 321 """Move parameters towards ``other``'s: θ ← (1-α)θ + αθ_other (same architecture).""" 322 return self.apply_edit(Edit("interpolate", select, args={"other": other, "alpha": alpha, 323 "select": select}, 324 label=f"interpolate α={alpha} towards {other.name}")) 325 326 def transplant(self, other: "Net", target: str, mapping: dict | None = None) -> "Net": 327 """Copy parameters of ``target`` (node or param pattern) from ``other``.""" 328 return self.apply_edit(Edit("transplant", target, args={"other": other, "mapping": mapping}, 329 label=f"transplant {target} from {other.name}")) 330 331 # ---------------------------------------------------------- activations 332 def intervene(self, targets, *interventions) -> InterventionHandle: 333 """Attach activation interventions (persistent until ``.remove()`` / end of ``with``).""" 334 ids = self._resolve_nodes(targets) 335 fns = [as_intervention(i) for i in interventions] 336 handles = [self.backend.add_intervention(nid, fn) for nid in ids for fn in fns] 337 return InterventionHandle(self, handles, f"{', '.join(map(repr, fns))} @ {ids}") 338 339 def profile(self, data, labels=None, **kw): 340 """The network over a dataset: per-unit statistics, dead units, the inputs that excite each unit most, a 2-D 341 map of the samples per layer and layer similarity (CKA) — :mod:`deepvis.monitor.profile`. Show it with 342 ``net.export_html(path, x, dataset=profile)``.""" 343 from .monitor.profile import profile 344 345 return profile(self, data, labels, **kw) 346 347 def monitor(self, *targets, stats=DEFAULT_STATS, keep: str = "last", grads: bool = False, 348 every: int = 1, start: bool = True) -> Monitor: 349 """Persistent activation monitor on nodes matching ``targets`` (default: all compute nodes).""" 350 if targets: 351 ids = self._resolve_nodes(list(targets)) 352 else: 353 ids = [n.id for n in self.graph.compute_nodes() if n.op in ("module", "function")] 354 ops = ("module", "function") if self.backend.function_taps else ("module",) 355 if targets and not self.backend.function_taps: 356 bad = [i for i in ids if self.graph.nodes[i].op == "function"] 357 if bad: 358 raise ValueError(f"{self.framework} monitors attach to modules; {bad} are functional ops. " 359 "Use net.trace(x) to record those.") 360 ids = [i for i in ids if self.graph.nodes[i].op in ops] 361 mon = Monitor(self, ids, tuple(stats), keep=keep, grads=grads, every=every) 362 return mon.start() if start else mon 363 364 def trace(self, *inputs, record: Any = "all", grads: bool = False, loss_fn: Callable | None = None, 365 capture_attention: bool = True, interventions: dict | None = None, **kwargs) -> Trace: 366 """Run once and record intermediates (``record`` = "all", node ids or patterns).""" 367 args = _as_args(inputs, self) if inputs else self.sample_input 368 if args is None: 369 raise ValueError("trace() needs an input") 370 if not self.backend.has_data: 371 from .errors import OptionError 372 373 raise OptionError("this model is on the meta device: it has shapes but no numbers to run.", 374 "its page shows the architecture, shapes and equations (net.export_html(path)); load " 375 "real weights to trace it.") 376 before = self._sample # a run that fails leaves the sample input as it was 377 if self._sample is None: 378 self._sample = args 379 try: 380 return self._trace(args, record, grads, loss_fn, capture_attention, interventions, kwargs) 381 except BaseException: 382 self._sample = before 383 raise 384 385 def _trace(self, args, record, grads, loss_fn, capture_attention, interventions, kwargs) -> Trace: 386 g = self.graph 387 if not any(n.out_shapes for n in g.compute_nodes()): 388 self.rebuild_graph(*args) 389 rec = record if record in ("all", None, True, False) else self._resolve_nodes(record) 390 ints = {} 391 for k, v in (interventions or {}).items(): 392 for nid in self._resolve_nodes(k): 393 ints.setdefault(nid, []).extend(as_intervention(i) for i in (v if isinstance(v, (list, tuple)) 394 else [v])) 395 from . import errors as E 396 397 if self.framework == "torch": 398 args = E.prepare_inputs(self.backend.model, args, "torch") 399 try: 400 res = self.backend.run(args, kwargs, record=rec, record_inputs=True, interventions=ints, grads=grads, 401 loss_fn=loss_fn, capture_attention=capture_attention) 402 except E.DeepvisError: 403 raise 404 except Exception as exc: # noqa: BLE001 405 failed = E.probe(self.backend.model, args, "torch") if self.framework == "torch" else exc 406 if failed is not None: 407 raise E.run_error(failed, args) from failed 408 raise E.trace_error(exc) from exc 409 self._last_args = args 410 return Trace(self, args, kwargs, res) 411 412 def attribute(self, *inputs, method: str = "integrated_gradients", target: int | None = None, sample: int = 0, 413 **kw): 414 """Which parts of the input made the model predict ``target`` (default: its prediction): an 415 :class:`~deepvis.interpret.Attribution` with ``.map`` shaped like the input (see :mod:`deepvis.interpret`).""" 416 from .interpret.attribution import attribute 417 418 return attribute(self, *inputs, method=method, target=target, sample=sample, **kw) 419 420 def head_importance(self, *inputs, sample: int = 0, max_heads: int = 256): 421 """How much the output moves when each attention head is switched off (see :mod:`deepvis.interpret`).""" 422 from .interpret.attention import head_importance 423 424 return head_importance(self, _as_args(inputs, self) if inputs else self.sample_input, sample=sample, 425 max_heads=max_heads) 426 427 def logit_lens(self, *inputs, **kw): 428 """What a language model would predict after each block (see :mod:`deepvis.monitor.lens`).""" 429 from .monitor.lens import logit_lens 430 431 return logit_lens(self, *(inputs or self.sample_input or ()), **kw) 432 433 # -------------------------------------------------------------- equations 434 def equation(self, mode: str = "system", **kw): 435 """Unroll the network into math. Modes: compact | system | expanded | scalar.""" 436 from .equations.unroll import unroll 437 438 return unroll(self, mode=mode, **kw) 439 440 # ------------------------------------------------------------------ viz 441 def show(self, *inputs, focus: str | None = None, trace: Trace | None = None, 442 monitor: Monitor | None = None, open_browser: bool | None = None, **kw): 443 """Interactive dashboard (inline in Jupyter, otherwise opens a browser tab). 444 445 Accepts the :meth:`export_html` options (views, start, style, title, note, depth, tensor_shapes). 446 """ 447 from .viz.html.dashboard import Dashboard 448 449 args = _as_args(inputs, self) if inputs else None 450 return Dashboard(self, args, focus=focus, trace=trace, monitor=monitor, **kw).display(open_browser) 451 452 def export_html(self, path: str, *inputs, views=None, start: str | None = None, style: str = "expressive", 453 title: str | None = None, note: str | None = None, depth=None, tensor_shapes: bool = True, 454 trace: Trace | None = None, monitor: Monitor | None = None, focus: str | None = None, 455 training=None, sample: int = 0, grads: bool = False, loss_fn: Callable | None = None, 456 tokenizer=None, labels=None, tokens=None, diffusion=None, attribution: bool = False, 457 heads: bool | None = None, compare=None, compare_names=None, lens_fn=None, dataset=None, 458 offline: bool | None = None, open_browser: bool = False) -> str: 459 """Write one self-contained, interactive HTML file and return its path. 460 461 views which tabs to include: any of "graph", "volumes", "neurons", "equations", "monitor" 462 start the tab the page opens on 463 style "expressive" (data-driven glyphs: activation curves, weight fans, 3-D tensors …) or "compact" 464 title, note header title and a short description shown in the overview panel 465 depth initial detail level: an int (collapse containers deeper than it) or "all" 466 tensor_shapes annotate edges with 3-D tensor cuboids 467 training a :class:`~deepvis.TrainingLog`: loss curves and per-layer learning dynamics (Monitor tab) 468 sample which sample of a batched input the views show (activations, glyphs, outputs) 469 grads also backpropagate ``loss_fn(output)`` (default: the output's sum): gradient flow per layer 470 (Monitor tab), ∂L/∂(output) of every layer and an input saliency map (side panel) 471 tokenizer a HuggingFace tokenizer (or ``id -> str``): token strings on the input and attention maps, 472 and the top next-token predictions of a language model (default: ``net.tokenizer``) 473 labels class names for the output (default: ``net.labels``); ``tokens`` labels the input directly 474 diffusion a :class:`~deepvis.diffusion.DiffusionRun`: the Diffusion tab (denoising process, x̂₀, ε̂) 475 attribution explain the top predictions: integrated gradients, saliency and Grad-CAM maps of the input 476 (PyTorch; the Output panel) 477 heads head importance in the Attention tab (each head switched off in turn): None = when the model 478 has ≤ 48 heads, True / False to force it 479 compare another version of this network — a model, a state_dict or a checkpoint path — for the 480 Compare tab: how far each layer's weights and activations moved, both outputs; 481 ``compare_names`` = ("before", "after") labels them 482 lens_fn ``h -> logits`` for the logit lens of a language model whose unembedding deepvis can't run 483 itself (JAX): e.g. ``lambda h: model.apply(variables, h, method=Model.unembed)`` 484 dataset a :class:`~deepvis.monitor.profile.DatasetProfile` from ``net.profile(data, labels)``: the 485 Dataset tab (a map of the samples per layer, layer similarity, dead units) and each layer's 486 most exciting inputs in its panel 487 offline inline the bundled KaTeX (~0.7 MB) so the page makes no network requests; default: 488 ``$DEEPVIS_OFFLINE`` (otherwise math loads from a CDN, with a plain-text fallback) 489 """ 490 import os 491 import webbrowser 492 493 from .viz.html.dashboard import Dashboard 494 495 args = _as_args(inputs, self) if inputs else (trace.args if trace is not None else self.sample_input) 496 d = Dashboard(self, args, focus=focus, trace=trace, monitor=monitor, style=style, tensor_shapes=tensor_shapes, 497 views=views, start=start, title=title, note=note, depth=depth, training=training, sample=sample, 498 grads=grads, loss_fn=loss_fn, tokenizer=tokenizer, labels=labels, tokens=tokens, 499 diffusion=diffusion, attribution=attribution, heads=heads, compare=compare, 500 compare_names=compare_names, lens_fn=lens_fn, dataset=dataset, offline=offline) 501 out = d.save(path) 502 if open_browser: 503 webbrowser.open("file://" + os.path.abspath(out)) 504 return out 505 506 def save_html(self, path: str, *inputs, **kw) -> str: 507 """Alias of :meth:`export_html`.""" 508 return self.export_html(path, *inputs, **kw) 509 510 def export_svg(self, path: str, *inputs, depth=None, direction: str = "TB", title: str | None = None, 511 subtitle: str | None = None, tensor_shapes: bool = True, legend: bool = True) -> str: 512 """Write a static architecture figure with the expressive glyphs: ``.svg``, ``.png`` or ``.pdf`` (for papers 513 and slides; needs ``cairosvg``), or ``.html`` wrapping the SVG. 514 515 With inputs the glyphs are data-driven (real activation ranges, input images, attention maps, outputs). 516 """ 517 from .viz.diagram import diagram_html, diagram_svg, svg_to_file 518 519 args = _as_args(inputs, self) if inputs else self.sample_input 520 svg = diagram_svg(self, args, depth=depth, direction=direction, title=title, subtitle=subtitle, 521 tensor_shapes=tensor_shapes, legend=legend) 522 low = str(path).lower() 523 if low.endswith((".png", ".pdf")): 524 return svg_to_file(svg, str(path)) 525 text = diagram_html(svg, title or self.name) if low.endswith((".html", ".htm")) else svg 526 from .viz.html.dashboard import write_text 527 528 return write_text(path, text) 529 530 def widget(self, *inputs, height: int = 820, **kw): 531 """The live page as a notebook widget — weight edits, interventions, the input playground, training — in 532 JupyterLab, Jupyter, VS Code notebooks and Colab, with no web server (needs ``anywidget``). Takes 533 :meth:`serve`'s options; ``widget.update(step, loss=…)`` records training progress.""" 534 from .viz.server import LiveServer 535 from .viz.widget import make_widget 536 537 args = _as_args(inputs, self) if inputs else self.sample_input 538 return make_widget(LiveServer(self, args, **kw), height=height) 539 540 def serve(self, *inputs, port: int = 0, open_browser: bool = True, **kw): 541 """Live dashboard with in-browser weight editing backed by this Python process. 542 543 Returns a :class:`~deepvis.viz.server.LiveServer`; call ``srv.update(step, loss=...)`` from a training 544 loop and the open page follows along (loss curves, per-layer learning dynamics, refreshed views). 545 546 Or let the page drive training: ``train_step=fn`` (``fn(step) -> {"loss": ..., ...}``, one optimization 547 step) adds Train / Pause / Step / Reset buttons; ``train_steps`` caps the run, ``train_reset()`` is called 548 after Reset restores the initial weights (e.g. to rebuild the optimizer), ``train_delay`` slows it down. 549 """ 550 from .viz.server import LiveServer 551 552 args = _as_args(inputs, self) if inputs else self.sample_input 553 return LiveServer(self, args, port=port, **kw).start(open_browser=open_browser) 554 555 def animate(self, kind: str = "forward", *inputs, path: str | None = None, quality: str = "low", **kw): 556 """Render a manim animation: forward | equation | focus | edit | architecture | volumes | training. 557 558 The videos narrate themselves along the bottom of the frame (plain words, real numbers); ``captions=False`` 559 turns that off.""" 560 from .anim.render import animate 561 562 args = _as_args(inputs, self) if inputs else self.sample_input 563 return animate(self, kind, args, path=path, quality=quality, **kw)
A wrapped PyTorch / JAX network.
Build with deepvis.wrap(). Highlights::
net.summary() # module tree
net["encoder.block2"] # focus on a sub-network (NodeView)
net["fc1.weight"][:, 3] = 0 # arbitrary weight surgery (undoable)
net.select("layers.*.fc*", kind="Linear").prune(0.3)
tr = net.trace(x) # every intermediate activation
with net.monitor("relu*") as mon: net(x) # persistent stats
with net.intervene("relu1", dv.ablate([2])): net(x)
net.equation(mode="expanded") # unroll into math
net.show(x) # interactive 3b1b-style dashboard
net.animate("forward", x, path="fwd.mp4") # manim video
55 def __init__(self, backend: Backend, sample_input: Any = None): 56 self.backend = backend 57 self.history = History(self) 58 self._monitors: list[Monitor] = [] 59 self._sample = None if sample_input is None else ( 60 sample_input if isinstance(sample_input, tuple) else (sample_input,)) 61 self._last_args: tuple | None = None 62 self._version = 0 63 self.tokenizer = None # optional: token strings / next-token predictions in pages (see export_html) 64 self.labels = None # optional: class names for the output 65 self.page: str | None = None # the file dv.visualize() wrote
85 def rebuild_graph(self, *inputs) -> ModelGraph: 86 """Re-trace the graph (e.g. with a new sample input to fill in shapes).""" 87 args = _as_args(inputs, self) if inputs else self._sample 88 if args: 89 self._sample = args 90 return self.backend.build_graph(*(args or ()))
Re-trace the graph (e.g. with a new sample input to fill in shapes).
110 def export(self): 111 """The (edited) model in native form: torch Module, (module, variables), eqx/nnx model, or params.""" 112 return self.backend.export()
The (edited) model in native form: torch Module, (module, variables), eqx/nnx model, or params.
114 def load(self, native) -> "Net": 115 """Load new weights in native form, e.g. after an optimizer step in a JAX training loop. 116 117 Accepts what :meth:`export` returns: flax ``variables`` (or ``params``), an nnx / equinox model, a params 118 pytree, or a torch ``state_dict`` / module. Not recorded as an edit. 119 """ 120 self.backend.load(native) 121 self._invalidate() 122 return self
124 def clone(self) -> "Net": 125 """Independent copy (weights copied); history is not carried over.""" 126 return Net(self.backend.clone(), self._sample)
Independent copy (weights copied); history is not carried over.
166 def select(self, pattern: str | Iterable[str] | None = None, kind: str | Iterable[str] | None = None, 167 where: Callable[[Node], bool] | None = None, leaves: bool = True) -> "Selection": 168 """Select nodes by path glob/regex, canonical kind and/or predicate.""" 169 g = self.graph 170 kinds = {kind} if isinstance(kind, str) else set(kind) if kind else None 171 pats = [pattern] if isinstance(pattern, str) else list(pattern) if pattern else None 172 ids = [] 173 for n in g.nodes.values(): 174 if leaves and not n.is_compute: 175 continue 176 if n.op in ("input", "output") and pats is None: 177 continue 178 if pats and not any(match(p, n.id) for p in pats): 179 continue 180 if kinds and n.kind not in kinds and n.type_name not in kinds: 181 continue 182 if where and not where(n): 183 continue 184 ids.append(n.id) 185 return Selection(self, ids)
Select nodes by path glob/regex, canonical kind and/or predicate.
209 def summary(self, show: bool = True) -> str: 210 """The network in one plain sentence, then a table of its layers, shapes and parameter counts.""" 211 from .viz.explain import describe 212 213 s = describe(self.graph, batched=self.framework != "equinox") + "\n" + self.graph.summary() 214 if show: 215 print(s) 216 return s
The network in one plain sentence, then a table of its layers, shapes and parameter counts.
218 def num_params(self, trainable_only: bool = True) -> int: 219 """Parameter count; ``trainable_only=False`` also counts buffers (e.g. BatchNorm running statistics).""" 220 infos = (self.backend.param_info(p) for p in self.backend.param_paths()) 221 return sum(int(np.prod(i.shape)) for i in infos if i.trainable or not trainable_only)
Parameter count; trainable_only=False also counts buffers (e.g. BatchNorm running statistics).
253 def apply_edit(self, edit: Edit | dict) -> "Net": 254 """Apply one edit (recorded for undo/redo).""" 255 if isinstance(edit, dict): 256 edit = Edit.from_dict(edit) 257 new = compute_edit(self, edit) 258 before = {p: self.backend.get_param(p) for p in new} 259 for p, v in new.items(): 260 self.backend.set_param(p, v) 261 self.history.record(edit, before, {p: v.copy() for p, v in new.items()}) 262 self._invalidate() 263 return self
Apply one edit (recorded for undo/redo).
265 def apply_edits(self, edits) -> "Net": 266 """Apply a list of edits / dicts, or a JSON file / string of them (see ``net.history.export()``).""" 267 for e in load_edits(edits): 268 self.apply_edit(e) 269 return self
Apply a list of edits / dicts, or a JSON file / string of them (see net.history.export()).
271 def edit(self, target: str, op: str | Callable, where=None, index=None, params=None, **args) -> "Net": 272 """``net.edit("fc1.weight", "scale", factor=2)`` or ``net.edit("fc*", lambda w: w.clip(-1, 1))``.""" 273 if callable(op): 274 args = {"fn": op} 275 op = "apply" 276 path, idx = split_index(target) 277 return self.apply_edit(Edit(op, path, index=index if index is not None else idx, args=args, 278 where=where, params=params))
net.edit("fc1.weight", "scale", factor=2) or net.edit("fc*", lambda w: w.clip(-1, 1)).
280 @contextlib.contextmanager 281 def edits(self): 282 """Temporary edits: everything applied inside the block is undone on exit.""" 283 start = self.history.pos 284 try: 285 yield self 286 finally: 287 self.history.undo(self.history.pos - start) 288 del self.history.entries[start:]
Temporary edits: everything applied inside the block is undone on exit.
296 def reset(self) -> None: 297 """Restore all edited parameters to their original values.""" 298 self.history.reset()
Restore all edited parameters to their original values.
303 def restore(self, snap: Snapshot) -> "Net": 304 changed = {p: v for p, v in snap.values.items() if not np.array_equal(self.backend.get_param(p), v)} 305 if changed: 306 self.apply_edit(Edit("load", list(changed), args={"values": changed}, 307 label=f"restore snapshot {snap.label}".strip())) 308 return self
316 def permute_neurons(self, node: str, perm) -> "Net": 317 """Permute a layer's output neurons and its consumers' inputs (function-preserving).""" 318 return self.apply_edit(Edit("permute_neurons", node, args={"perm": np.asarray(perm).tolist()}))
Permute a layer's output neurons and its consumers' inputs (function-preserving).
320 def interpolate(self, other: "Net", alpha: float = 0.5, select: str = "**") -> "Net": 321 """Move parameters towards ``other``'s: θ ← (1-α)θ + αθ_other (same architecture).""" 322 return self.apply_edit(Edit("interpolate", select, args={"other": other, "alpha": alpha, 323 "select": select}, 324 label=f"interpolate α={alpha} towards {other.name}"))
Move parameters towards other's: θ ← (1-α)θ + αθ_other (same architecture).
326 def transplant(self, other: "Net", target: str, mapping: dict | None = None) -> "Net": 327 """Copy parameters of ``target`` (node or param pattern) from ``other``.""" 328 return self.apply_edit(Edit("transplant", target, args={"other": other, "mapping": mapping}, 329 label=f"transplant {target} from {other.name}"))
Copy parameters of target (node or param pattern) from other.
332 def intervene(self, targets, *interventions) -> InterventionHandle: 333 """Attach activation interventions (persistent until ``.remove()`` / end of ``with``).""" 334 ids = self._resolve_nodes(targets) 335 fns = [as_intervention(i) for i in interventions] 336 handles = [self.backend.add_intervention(nid, fn) for nid in ids for fn in fns] 337 return InterventionHandle(self, handles, f"{', '.join(map(repr, fns))} @ {ids}")
Attach activation interventions (persistent until .remove() / end of with).
339 def profile(self, data, labels=None, **kw): 340 """The network over a dataset: per-unit statistics, dead units, the inputs that excite each unit most, a 2-D 341 map of the samples per layer and layer similarity (CKA) — :mod:`deepvis.monitor.profile`. Show it with 342 ``net.export_html(path, x, dataset=profile)``.""" 343 from .monitor.profile import profile 344 345 return profile(self, data, labels, **kw)
The network over a dataset: per-unit statistics, dead units, the inputs that excite each unit most, a 2-D
map of the samples per layer and layer similarity (CKA) — deepvis.monitor.profile. Show it with
net.export_html(path, x, dataset=profile).
347 def monitor(self, *targets, stats=DEFAULT_STATS, keep: str = "last", grads: bool = False, 348 every: int = 1, start: bool = True) -> Monitor: 349 """Persistent activation monitor on nodes matching ``targets`` (default: all compute nodes).""" 350 if targets: 351 ids = self._resolve_nodes(list(targets)) 352 else: 353 ids = [n.id for n in self.graph.compute_nodes() if n.op in ("module", "function")] 354 ops = ("module", "function") if self.backend.function_taps else ("module",) 355 if targets and not self.backend.function_taps: 356 bad = [i for i in ids if self.graph.nodes[i].op == "function"] 357 if bad: 358 raise ValueError(f"{self.framework} monitors attach to modules; {bad} are functional ops. " 359 "Use net.trace(x) to record those.") 360 ids = [i for i in ids if self.graph.nodes[i].op in ops] 361 mon = Monitor(self, ids, tuple(stats), keep=keep, grads=grads, every=every) 362 return mon.start() if start else mon
Persistent activation monitor on nodes matching targets (default: all compute nodes).
364 def trace(self, *inputs, record: Any = "all", grads: bool = False, loss_fn: Callable | None = None, 365 capture_attention: bool = True, interventions: dict | None = None, **kwargs) -> Trace: 366 """Run once and record intermediates (``record`` = "all", node ids or patterns).""" 367 args = _as_args(inputs, self) if inputs else self.sample_input 368 if args is None: 369 raise ValueError("trace() needs an input") 370 if not self.backend.has_data: 371 from .errors import OptionError 372 373 raise OptionError("this model is on the meta device: it has shapes but no numbers to run.", 374 "its page shows the architecture, shapes and equations (net.export_html(path)); load " 375 "real weights to trace it.") 376 before = self._sample # a run that fails leaves the sample input as it was 377 if self._sample is None: 378 self._sample = args 379 try: 380 return self._trace(args, record, grads, loss_fn, capture_attention, interventions, kwargs) 381 except BaseException: 382 self._sample = before 383 raise
Run once and record intermediates (record = "all", node ids or patterns).
412 def attribute(self, *inputs, method: str = "integrated_gradients", target: int | None = None, sample: int = 0, 413 **kw): 414 """Which parts of the input made the model predict ``target`` (default: its prediction): an 415 :class:`~deepvis.interpret.Attribution` with ``.map`` shaped like the input (see :mod:`deepvis.interpret`).""" 416 from .interpret.attribution import attribute 417 418 return attribute(self, *inputs, method=method, target=target, sample=sample, **kw)
Which parts of the input made the model predict target (default: its prediction): an
~deepvis.interpret.Attribution with .map shaped like the input (see deepvis.interpret).
420 def head_importance(self, *inputs, sample: int = 0, max_heads: int = 256): 421 """How much the output moves when each attention head is switched off (see :mod:`deepvis.interpret`).""" 422 from .interpret.attention import head_importance 423 424 return head_importance(self, _as_args(inputs, self) if inputs else self.sample_input, sample=sample, 425 max_heads=max_heads)
How much the output moves when each attention head is switched off (see deepvis.interpret).
427 def logit_lens(self, *inputs, **kw): 428 """What a language model would predict after each block (see :mod:`deepvis.monitor.lens`).""" 429 from .monitor.lens import logit_lens 430 431 return logit_lens(self, *(inputs or self.sample_input or ()), **kw)
What a language model would predict after each block (see deepvis.monitor.lens).
434 def equation(self, mode: str = "system", **kw): 435 """Unroll the network into math. Modes: compact | system | expanded | scalar.""" 436 from .equations.unroll import unroll 437 438 return unroll(self, mode=mode, **kw)
Unroll the network into math. Modes: compact | system | expanded | scalar.
441 def show(self, *inputs, focus: str | None = None, trace: Trace | None = None, 442 monitor: Monitor | None = None, open_browser: bool | None = None, **kw): 443 """Interactive dashboard (inline in Jupyter, otherwise opens a browser tab). 444 445 Accepts the :meth:`export_html` options (views, start, style, title, note, depth, tensor_shapes). 446 """ 447 from .viz.html.dashboard import Dashboard 448 449 args = _as_args(inputs, self) if inputs else None 450 return Dashboard(self, args, focus=focus, trace=trace, monitor=monitor, **kw).display(open_browser)
Interactive dashboard (inline in Jupyter, otherwise opens a browser tab).
Accepts the export_html() options (views, start, style, title, note, depth, tensor_shapes).
452 def export_html(self, path: str, *inputs, views=None, start: str | None = None, style: str = "expressive", 453 title: str | None = None, note: str | None = None, depth=None, tensor_shapes: bool = True, 454 trace: Trace | None = None, monitor: Monitor | None = None, focus: str | None = None, 455 training=None, sample: int = 0, grads: bool = False, loss_fn: Callable | None = None, 456 tokenizer=None, labels=None, tokens=None, diffusion=None, attribution: bool = False, 457 heads: bool | None = None, compare=None, compare_names=None, lens_fn=None, dataset=None, 458 offline: bool | None = None, open_browser: bool = False) -> str: 459 """Write one self-contained, interactive HTML file and return its path. 460 461 views which tabs to include: any of "graph", "volumes", "neurons", "equations", "monitor" 462 start the tab the page opens on 463 style "expressive" (data-driven glyphs: activation curves, weight fans, 3-D tensors …) or "compact" 464 title, note header title and a short description shown in the overview panel 465 depth initial detail level: an int (collapse containers deeper than it) or "all" 466 tensor_shapes annotate edges with 3-D tensor cuboids 467 training a :class:`~deepvis.TrainingLog`: loss curves and per-layer learning dynamics (Monitor tab) 468 sample which sample of a batched input the views show (activations, glyphs, outputs) 469 grads also backpropagate ``loss_fn(output)`` (default: the output's sum): gradient flow per layer 470 (Monitor tab), ∂L/∂(output) of every layer and an input saliency map (side panel) 471 tokenizer a HuggingFace tokenizer (or ``id -> str``): token strings on the input and attention maps, 472 and the top next-token predictions of a language model (default: ``net.tokenizer``) 473 labels class names for the output (default: ``net.labels``); ``tokens`` labels the input directly 474 diffusion a :class:`~deepvis.diffusion.DiffusionRun`: the Diffusion tab (denoising process, x̂₀, ε̂) 475 attribution explain the top predictions: integrated gradients, saliency and Grad-CAM maps of the input 476 (PyTorch; the Output panel) 477 heads head importance in the Attention tab (each head switched off in turn): None = when the model 478 has ≤ 48 heads, True / False to force it 479 compare another version of this network — a model, a state_dict or a checkpoint path — for the 480 Compare tab: how far each layer's weights and activations moved, both outputs; 481 ``compare_names`` = ("before", "after") labels them 482 lens_fn ``h -> logits`` for the logit lens of a language model whose unembedding deepvis can't run 483 itself (JAX): e.g. ``lambda h: model.apply(variables, h, method=Model.unembed)`` 484 dataset a :class:`~deepvis.monitor.profile.DatasetProfile` from ``net.profile(data, labels)``: the 485 Dataset tab (a map of the samples per layer, layer similarity, dead units) and each layer's 486 most exciting inputs in its panel 487 offline inline the bundled KaTeX (~0.7 MB) so the page makes no network requests; default: 488 ``$DEEPVIS_OFFLINE`` (otherwise math loads from a CDN, with a plain-text fallback) 489 """ 490 import os 491 import webbrowser 492 493 from .viz.html.dashboard import Dashboard 494 495 args = _as_args(inputs, self) if inputs else (trace.args if trace is not None else self.sample_input) 496 d = Dashboard(self, args, focus=focus, trace=trace, monitor=monitor, style=style, tensor_shapes=tensor_shapes, 497 views=views, start=start, title=title, note=note, depth=depth, training=training, sample=sample, 498 grads=grads, loss_fn=loss_fn, tokenizer=tokenizer, labels=labels, tokens=tokens, 499 diffusion=diffusion, attribution=attribution, heads=heads, compare=compare, 500 compare_names=compare_names, lens_fn=lens_fn, dataset=dataset, offline=offline) 501 out = d.save(path) 502 if open_browser: 503 webbrowser.open("file://" + os.path.abspath(out)) 504 return out
Write one self-contained, interactive HTML file and return its path.
views which tabs to include: any of "graph", "volumes", "neurons", "equations", "monitor"
start the tab the page opens on
style "expressive" (data-driven glyphs: activation curves, weight fans, 3-D tensors …) or "compact"
title, note header title and a short description shown in the overview panel
depth initial detail level: an int (collapse containers deeper than it) or "all"
tensor_shapes annotate edges with 3-D tensor cuboids
training a ~deepvis.TrainingLog: loss curves and per-layer learning dynamics (Monitor tab)
sample which sample of a batched input the views show (activations, glyphs, outputs)
grads also backpropagate loss_fn(output) (default: the output's sum): gradient flow per layer
(Monitor tab), ∂L/∂(output) of every layer and an input saliency map (side panel)
tokenizer a HuggingFace tokenizer (or id -> str): token strings on the input and attention maps,
and the top next-token predictions of a language model (default: net.tokenizer)
labels class names for the output (default: net.labels); tokens labels the input directly
diffusion a ~deepvis.diffusion.DiffusionRun: the Diffusion tab (denoising process, x̂₀, ε̂)
attribution explain the top predictions: integrated gradients, saliency and Grad-CAM maps of the input
(PyTorch; the Output panel)
heads head importance in the Attention tab (each head switched off in turn): None = when the model
has ≤ 48 heads, True / False to force it
compare another version of this network — a model, a state_dict or a checkpoint path — for the
Compare tab: how far each layer's weights and activations moved, both outputs;
compare_names = ("before", "after") labels them
lens_fn h -> logits for the logit lens of a language model whose unembedding deepvis can't run
itself (JAX): e.g. lambda h: model.apply(variables, h, method=Model.unembed)
dataset a ~deepvis.monitor.profile.DatasetProfile from net.profile(data, labels): the
Dataset tab (a map of the samples per layer, layer similarity, dead units) and each layer's
most exciting inputs in its panel
offline inline the bundled KaTeX (~0.7 MB) so the page makes no network requests; default:
$DEEPVIS_OFFLINE (otherwise math loads from a CDN, with a plain-text fallback)
506 def save_html(self, path: str, *inputs, **kw) -> str: 507 """Alias of :meth:`export_html`.""" 508 return self.export_html(path, *inputs, **kw)
Alias of export_html().
510 def export_svg(self, path: str, *inputs, depth=None, direction: str = "TB", title: str | None = None, 511 subtitle: str | None = None, tensor_shapes: bool = True, legend: bool = True) -> str: 512 """Write a static architecture figure with the expressive glyphs: ``.svg``, ``.png`` or ``.pdf`` (for papers 513 and slides; needs ``cairosvg``), or ``.html`` wrapping the SVG. 514 515 With inputs the glyphs are data-driven (real activation ranges, input images, attention maps, outputs). 516 """ 517 from .viz.diagram import diagram_html, diagram_svg, svg_to_file 518 519 args = _as_args(inputs, self) if inputs else self.sample_input 520 svg = diagram_svg(self, args, depth=depth, direction=direction, title=title, subtitle=subtitle, 521 tensor_shapes=tensor_shapes, legend=legend) 522 low = str(path).lower() 523 if low.endswith((".png", ".pdf")): 524 return svg_to_file(svg, str(path)) 525 text = diagram_html(svg, title or self.name) if low.endswith((".html", ".htm")) else svg 526 from .viz.html.dashboard import write_text 527 528 return write_text(path, text)
Write a static architecture figure with the expressive glyphs: .svg, .png or .pdf (for papers
and slides; needs cairosvg), or .html wrapping the SVG.
With inputs the glyphs are data-driven (real activation ranges, input images, attention maps, outputs).
530 def widget(self, *inputs, height: int = 820, **kw): 531 """The live page as a notebook widget — weight edits, interventions, the input playground, training — in 532 JupyterLab, Jupyter, VS Code notebooks and Colab, with no web server (needs ``anywidget``). Takes 533 :meth:`serve`'s options; ``widget.update(step, loss=…)`` records training progress.""" 534 from .viz.server import LiveServer 535 from .viz.widget import make_widget 536 537 args = _as_args(inputs, self) if inputs else self.sample_input 538 return make_widget(LiveServer(self, args, **kw), height=height)
The live page as a notebook widget — weight edits, interventions, the input playground, training — in
JupyterLab, Jupyter, VS Code notebooks and Colab, with no web server (needs anywidget). Takes
serve()'s options; widget.update(step, loss=…) records training progress.
540 def serve(self, *inputs, port: int = 0, open_browser: bool = True, **kw): 541 """Live dashboard with in-browser weight editing backed by this Python process. 542 543 Returns a :class:`~deepvis.viz.server.LiveServer`; call ``srv.update(step, loss=...)`` from a training 544 loop and the open page follows along (loss curves, per-layer learning dynamics, refreshed views). 545 546 Or let the page drive training: ``train_step=fn`` (``fn(step) -> {"loss": ..., ...}``, one optimization 547 step) adds Train / Pause / Step / Reset buttons; ``train_steps`` caps the run, ``train_reset()`` is called 548 after Reset restores the initial weights (e.g. to rebuild the optimizer), ``train_delay`` slows it down. 549 """ 550 from .viz.server import LiveServer 551 552 args = _as_args(inputs, self) if inputs else self.sample_input 553 return LiveServer(self, args, port=port, **kw).start(open_browser=open_browser)
Live dashboard with in-browser weight editing backed by this Python process.
Returns a ~deepvis.viz.server.LiveServer; call srv.update(step, loss=...) from a training
loop and the open page follows along (loss curves, per-layer learning dynamics, refreshed views).
Or let the page drive training: train_step=fn (fn(step) -> {"loss": ..., ...}, one optimization
step) adds Train / Pause / Step / Reset buttons; train_steps caps the run, train_reset() is called
after Reset restores the initial weights (e.g. to rebuild the optimizer), train_delay slows it down.
555 def animate(self, kind: str = "forward", *inputs, path: str | None = None, quality: str = "low", **kw): 556 """Render a manim animation: forward | equation | focus | edit | architecture | volumes | training. 557 558 The videos narrate themselves along the bottom of the frame (plain words, real numbers); ``captions=False`` 559 turns that off.""" 560 from .anim.render import animate 561 562 args = _as_args(inputs, self) if inputs else self.sample_input 563 return animate(self, kind, args, path=path, quality=quality, **kw)
Render a manim animation: forward | equation | focus | edit | architecture | volumes | training.
The videos narrate themselves along the bottom of the frame (plain words, real numbers); captions=False
turns that off.
566class NodeView(EditMethods): 567 """A focused sub-network / layer. Most :class:`Net` verbs are scoped to it.""" 568 569 def __init__(self, net: Net, path: str): 570 if path not in net.graph.nodes: 571 raise KeyError(path) 572 self.net = net 573 self.path = path 574 575 @property 576 def node(self) -> Node: 577 return self.net.graph.nodes[self.path] 578 579 @property 580 def kind(self) -> str: 581 return self.node.kind 582 583 @property 584 def children(self) -> list["NodeView"]: 585 return [NodeView(self.net, c) for c in self.node.children] 586 587 @property 588 def graph(self) -> ModelGraph: 589 return self.net.graph.subgraph(self.path) 590 591 def __getitem__(self, key: str): 592 return self.net[f"{self.path}.{key}" if self.path else key] 593 594 def __setitem__(self, key: str, value) -> None: 595 self.net[f"{self.path}.{key}" if self.path else key] = value 596 597 def params(self) -> dict[str, ParamRef]: 598 if self.node.is_compute: 599 return {k: ParamRef(self.net, v.path) for k, v in self.node.params.items()} 600 prefix = f"{self.path}." if self.path else "" 601 return {p[len(prefix):]: ParamRef(self.net, p) for p in self.net.backend.param_paths() 602 if p.startswith(prefix)} 603 604 def _role(self, role: str) -> ParamRef: 605 info = self.node.role_param(role) 606 if info is None: 607 raise AttributeError(f"{self.path!r} ({self.kind}) has no {role!r} parameter") 608 return ParamRef(self.net, info.path) 609 610 @property 611 def weight(self) -> ParamRef: 612 return self._role("weight") 613 614 @property 615 def bias(self) -> ParamRef: 616 return self._role("bias") 617 618 def weight_matrix(self) -> np.ndarray: 619 """Weight in canonical (out, in, ...) orientation regardless of framework.""" 620 r = self.node.roles["weight"] 621 w = self.weight.numpy() 622 if r.out_axis is None: 623 return w 624 order = [r.out_axis % w.ndim] + ([r.in_axis % w.ndim] if r.in_axis is not None else []) 625 order += [i for i in range(w.ndim) if i not in order] 626 return np.transpose(w, order) 627 628 def neurons(self, idx) -> NeuronSelection: 629 return NeuronSelection(self.net, self.path, idx) 630 631 def neuron(self, i: int) -> NeuronSelection: 632 return NeuronSelection(self.net, self.path, [i]) 633 634 def prune_neurons(self, amount: float = 0.5, by: str = "l2") -> "NodeView": 635 """Structured pruning: remove (zero) the output neurons with the smallest weight norm.""" 636 w = self.weight_matrix() 637 flat = w.reshape(w.shape[0], -1) 638 score = np.linalg.norm(flat, axis=1) if by == "l2" else np.abs(flat).sum(1) 639 k = int(round(amount * len(score))) 640 if k: 641 self.neurons(np.argsort(score)[:k].tolist()).zero() 642 return self 643 644 def _edit(self, op, args, where=None, params=None, label=None): 645 if self.node.is_container: 646 target = f"{self.path}.**" if self.path else "**" 647 else: 648 target = self.path 649 self.net.apply_edit(Edit(op, target, args=args, where=where, params=params, label=label)) 650 return self 651 652 def intervene(self, *interventions) -> InterventionHandle: 653 return self.net.intervene(self.path, *interventions) 654 655 def monitor(self, **kw) -> Monitor: 656 ids = [self.path] if self.node.is_compute else [ 657 d for d in self.net.graph.descendants(self.path) if self.net.graph.nodes[d].op in ("module", "function")] 658 return self.net.monitor(*ids, **kw) 659 660 def trace(self, *inputs, **kw) -> Trace: 661 ids = [self.path] if self.node.is_compute else [ 662 d for d in self.net.graph.descendants(self.path) if self.net.graph.nodes[d].is_compute] 663 return self.net.trace(*inputs, record=ids, **kw) 664 665 def equation(self, mode: str = "system", **kw): 666 return self.net.equation(mode=mode, focus=self.path, **kw) 667 668 def show(self, *inputs, **kw): 669 return self.net.show(*inputs, focus=self.path, **kw) 670 671 def animate(self, kind: str = "focus", *inputs, **kw): 672 return self.net.animate(kind, *inputs, focus=self.path, **kw) 673 674 def __repr__(self) -> str: 675 n = self.node 676 shp = f" → {tuple(n.out_shapes[0])}" if n.out_shapes and n.out_shapes[0] else "" 677 return f"NodeView({self.path or '<root>'}: {n.kind}{shp}, params={n.n_params:,})"
A focused sub-network / layer. Most Net verbs are scoped to it.
597 def params(self) -> dict[str, ParamRef]: 598 if self.node.is_compute: 599 return {k: ParamRef(self.net, v.path) for k, v in self.node.params.items()} 600 prefix = f"{self.path}." if self.path else "" 601 return {p[len(prefix):]: ParamRef(self.net, p) for p in self.net.backend.param_paths() 602 if p.startswith(prefix)}
618 def weight_matrix(self) -> np.ndarray: 619 """Weight in canonical (out, in, ...) orientation regardless of framework.""" 620 r = self.node.roles["weight"] 621 w = self.weight.numpy() 622 if r.out_axis is None: 623 return w 624 order = [r.out_axis % w.ndim] + ([r.in_axis % w.ndim] if r.in_axis is not None else []) 625 order += [i for i in range(w.ndim) if i not in order] 626 return np.transpose(w, order)
Weight in canonical (out, in, ...) orientation regardless of framework.
634 def prune_neurons(self, amount: float = 0.5, by: str = "l2") -> "NodeView": 635 """Structured pruning: remove (zero) the output neurons with the smallest weight norm.""" 636 w = self.weight_matrix() 637 flat = w.reshape(w.shape[0], -1) 638 score = np.linalg.norm(flat, axis=1) if by == "l2" else np.abs(flat).sum(1) 639 k = int(round(amount * len(score))) 640 if k: 641 self.neurons(np.argsort(score)[:k].tolist()).zero() 642 return self
Structured pruning: remove (zero) the output neurons with the smallest weight norm.
680class Selection(EditMethods): 681 """Several nodes at once; edits and interventions apply to each.""" 682 683 def __init__(self, net: Net, ids: list[str]): 684 self.net = net 685 self.ids = ids 686 687 def __len__(self) -> int: 688 return len(self.ids) 689 690 def __iter__(self): 691 return (NodeView(self.net, i) for i in self.ids) 692 693 def __getitem__(self, i): 694 return NodeView(self.net, self.ids[i]) 695 696 @property 697 def paths(self) -> list[str]: 698 return list(self.ids) 699 700 def params(self) -> dict[str, ParamRef]: 701 out = {} 702 for i in self.ids: 703 out.update({v.path: ParamRef(self.net, v.path) for v in self.net.graph.nodes[i].params.values()}) 704 return out 705 706 def _edit(self, op, args, where=None, params=None, label=None): 707 targets = [i for i in self.ids if self.net.graph.nodes[i].params] 708 if not targets: 709 raise ValueError("selection contains no parameterized nodes") 710 self.net.apply_edit(Edit(op, targets, args=args, where=where, params=params, label=label)) 711 return self 712 713 def intervene(self, *interventions) -> InterventionHandle: 714 return self.net.intervene(self.ids, *interventions) 715 716 def monitor(self, **kw) -> Monitor: 717 return self.net.monitor(*self.ids, **kw) 718 719 def show(self, *inputs, **kw): 720 return self.net.show(*inputs, highlight=self.ids, **kw) 721 722 def __repr__(self) -> str: 723 return f"Selection({len(self.ids)} nodes: {self.ids[:6]}{'…' if len(self.ids) > 6 else ''})"
Several nodes at once; edits and interventions apply to each.
88class ParamRef(EditMethods): 89 """A parameter (optionally a numpy-style region of it) that can be read and edited. 90 91 >>> w = net["fc1.weight"] # whole tensor 92 >>> w[:, 3] = 0 # slice assignment, recorded in history 93 >>> w[0:8].noise(0.05, seed=0) # region edits 94 >>> w *= 0.5 # in-place arithmetic 95 """ 96 97 def __init__(self, net: "Net", path: str, index: Any = None): 98 self.net = net 99 self.path = path 100 self.index = index 101 102 # ------------------------------------------------------------- reading 103 @property 104 def info(self): 105 return self.net.backend.param_info(self.path) 106 107 def numpy(self) -> np.ndarray: 108 full = self.net.backend.get_param(self.path) 109 return full if self.index is None else np.asarray(full[normalize_index(self.index)]).copy() 110 111 @property 112 def value(self) -> np.ndarray: 113 return self.numpy() 114 115 @property 116 def shape(self) -> tuple: 117 return self.numpy().shape if self.index is not None else tuple(self.info.shape) 118 119 @property 120 def dtype(self): 121 return self.info.dtype 122 123 def __array__(self, dtype=None, copy=None): 124 a = self.numpy() 125 return a.astype(dtype) if dtype is not None else a 126 127 def stats(self) -> dict: 128 return stats(self.numpy(), ("mean", "std", "min", "max", "norm", "sparsity")) 129 130 def histogram(self, bins: int = 40) -> dict: 131 return histogram(self.numpy(), bins) 132 133 @property 134 def native(self): 135 """The framework-native tensor/array (whole parameter).""" 136 getter = getattr(self.net.backend, "get_native_param", None) 137 return getter(self.path) if getter else self.net.backend.get_param(self.path) 138 139 # ------------------------------------------------------------ indexing 140 def __getitem__(self, idx) -> "ParamRef": 141 if self.index is not None: 142 raise IndexError("chained indexing is not supported; use a single index expression") 143 return ParamRef(self.net, self.path, idx) 144 145 def __setitem__(self, idx, value) -> None: 146 if self.index is not None: 147 raise IndexError("chained indexing is not supported; use a single index expression") 148 if isinstance(value, ParamRef) and value.path == self.path and _same_index(value.index, idx): 149 return # ``w[i] *= 2`` — the in-place operator already applied (and recorded) the edit 150 ParamRef(self.net, self.path, idx).set(value) 151 152 # -------------------------------------------------------------- edits 153 def _edit(self, op, args, where=None, params=None, label=None): 154 self.net.apply_edit(Edit(op, self.path, index=self.index, args=args, where=where, label=label)) 155 return self 156 157 def __imul__(self, other): 158 return self.scale(other) 159 160 def __itruediv__(self, other): 161 return self.scale(1.0 / other) 162 163 def __iadd__(self, other): 164 return self.add(other) 165 166 def __isub__(self, other): 167 return self.add(-np.asarray(other)) 168 169 # ------------------------------------------------------------- display 170 def __repr__(self) -> str: 171 s = self.stats() 172 idx = format_index(self.index) if self.index is not None else "" 173 return (f"ParamRef({self.path}{idx or ''}, shape={self.shape}, mean={s['mean']:.4g}, " 174 f"std={s['std']:.4g}, min={s['min']:.4g}, max={s['max']:.4g})") 175 176 def show(self, **kw): 177 return self.net.show(focus=self.info.module, **kw)
A parameter (optionally a numpy-style region of it) that can be read and edited.
>>> w = net["fc1.weight"] # whole tensor
>>> w[:, 3] = 0 # slice assignment, recorded in history
>>> w[0:8].noise(0.05, seed=0) # region edits
>>> w *= 0.5 # in-place arithmetic
133 @property 134 def native(self): 135 """The framework-native tensor/array (whole parameter).""" 136 getter = getattr(self.net.backend, "get_native_param", None) 137 return getter(self.path) if getter else self.net.backend.get_param(self.path)
The framework-native tensor/array (whole parameter).
95class Monitor: 96 """Persistent activation monitor. 97 98 >>> mon = net.monitor("fc*", "relu*", stats=("mean", "std", "sparsity")) 99 >>> for x, y in loader: # call the model as usual 100 ... loss = loss_fn(model(x), y); ... 101 ... mon.step() # optional: mark training steps 102 >>> mon["relu1"].series("sparsity") # dead-ReLU fraction over time 103 >>> mon.stop() 104 """ 105 106 def __init__(self, net: "Net", node_ids: list[str], stats_: tuple = DEFAULT_STATS, keep: str = "last", 107 grads: bool = False, every: int = 1): 108 if keep not in ("last", "all", "none"): 109 raise ValueError("keep must be 'last', 'all' or 'none'") 110 self.net = net 111 self.node_ids = node_ids 112 self.stats = tuple(stats_) 113 self.keep = keep 114 self.grads = grads 115 self.every = max(1, int(every)) 116 self.records: dict[str, Record] = {nid: Record(nid) for nid in node_ids} 117 self._handles: list[int] = [] 118 self.step_count = 0 119 120 # -------------------------------------------------------------- control 121 def start(self) -> "Monitor": 122 if not self._handles: 123 self._handles = [self.net.backend.add_tap(nid, self._observe) for nid in self.node_ids] 124 self.net._monitors.append(self) 125 return self 126 127 def stop(self) -> "Monitor": 128 for h in self._handles: 129 self.net.backend.remove(h) 130 self._handles = [] 131 if self in self.net._monitors: 132 self.net._monitors.remove(self) 133 return self 134 135 @property 136 def active(self) -> bool: 137 return bool(self._handles) 138 139 def __enter__(self) -> "Monitor": 140 return self.start() 141 142 def __exit__(self, *exc) -> None: 143 self.stop() 144 145 def step(self, n: int = 1) -> None: 146 self.step_count += n 147 148 def reset(self) -> None: 149 self.records = {nid: Record(nid) for nid in self.node_ids} 150 self.step_count = 0 151 152 # ------------------------------------------------------------ recording 153 def _observe(self, nid: str, out: Any, inp: Any) -> None: 154 rec = self.records[nid] 155 rec.calls += 1 156 if (rec.calls - 1) % self.every: 157 return 158 arr = to_numpy(out) 159 for k, v in stats(arr, self.stats).items(): 160 rec.history.setdefault(k, []).append(v) 161 rec.steps.append(self.step_count) 162 if self.keep == "last": 163 rec.last = np.array(arr, copy=True) 164 rec.last_input = to_numpy(inp).copy() if inp is not None and hasattr(inp, "shape") else None 165 elif self.keep == "all": 166 rec.last = np.array(arr, copy=True) 167 rec.all.append(rec.last) 168 if self.grads and getattr(out, "requires_grad", False) and hasattr(out, "register_hook"): 169 def on_grad(g, _rec=rec): 170 for k, v in stats(to_numpy(g), ("mean", "std", "norm")).items(): 171 _rec.grad_history.setdefault(k, []).append(v) 172 out.register_hook(on_grad) 173 174 # -------------------------------------------------------------- access 175 def __getitem__(self, node_id: str) -> Record: 176 if node_id in self.records: 177 return self.records[node_id] 178 from ..core.selectors import filter_paths 179 180 m = filter_paths(node_id, list(self.records)) 181 if len(m) == 1: 182 return self.records[m[0]] 183 raise KeyError(node_id) 184 185 def __iter__(self): 186 return iter(self.records.values()) 187 188 def table(self) -> str: 189 which = self.stats 190 head = f"{'node':<32} {'calls':>6}" + "".join(f"{w:>11}" for w in which) 191 lines = [head, "─" * len(head)] 192 for nid, rec in self.records.items(): 193 vals = "".join(f"{rec.history[w][-1]:>11.4g}" if rec.history.get(w) else f"{'—':>11}" for w in which) 194 lines.append(f"{nid[:32]:<32} {rec.calls:>6}{vals}") 195 return "\n".join(lines) 196 197 def to_dict(self, max_points: int = 400) -> dict: 198 out = {} 199 for nid, rec in self.records.items(): 200 hist = {} 201 for k, v in rec.history.items(): 202 arr = np.asarray(v, dtype=float) 203 if len(arr) > max_points: 204 idx = np.linspace(0, len(arr) - 1, max_points).astype(int) 205 arr = arr[idx] 206 hist[k] = np.nan_to_num(arr).round(6).tolist() 207 out[nid] = {"calls": rec.calls, "history": hist, 208 "grad_history": {k: np.nan_to_num(np.asarray(v[-max_points:])).round(6).tolist() 209 for k, v in rec.grad_history.items()}, 210 "hist": rec.histogram() if rec.last is not None else None} 211 return out 212 213 def __repr__(self) -> str: 214 state = "active" if self.active else "stopped" 215 return f"Monitor({len(self.node_ids)} nodes, {state}, steps={self.step_count})" 216 217 def show(self, **kw): 218 return self.net.show(monitor=self, **kw)
Persistent activation monitor.
>>> mon = net.monitor("fc*", "relu*", stats=("mean", "std", "sparsity"))
>>> for x, y in loader: # call the model as usual
... loss = loss_fn(model(x), y); ...
... mon.step() # optional: mark training steps
>>> mon["relu1"].series("sparsity") # dead-ReLU fraction over time
>>> mon.stop()
106 def __init__(self, net: "Net", node_ids: list[str], stats_: tuple = DEFAULT_STATS, keep: str = "last", 107 grads: bool = False, every: int = 1): 108 if keep not in ("last", "all", "none"): 109 raise ValueError("keep must be 'last', 'all' or 'none'") 110 self.net = net 111 self.node_ids = node_ids 112 self.stats = tuple(stats_) 113 self.keep = keep 114 self.grads = grads 115 self.every = max(1, int(every)) 116 self.records: dict[str, Record] = {nid: Record(nid) for nid in node_ids} 117 self._handles: list[int] = [] 118 self.step_count = 0
188 def table(self) -> str: 189 which = self.stats 190 head = f"{'node':<32} {'calls':>6}" + "".join(f"{w:>11}" for w in which) 191 lines = [head, "─" * len(head)] 192 for nid, rec in self.records.items(): 193 vals = "".join(f"{rec.history[w][-1]:>11.4g}" if rec.history.get(w) else f"{'—':>11}" for w in which) 194 lines.append(f"{nid[:32]:<32} {rec.calls:>6}{vals}") 195 return "\n".join(lines)
197 def to_dict(self, max_points: int = 400) -> dict: 198 out = {} 199 for nid, rec in self.records.items(): 200 hist = {} 201 for k, v in rec.history.items(): 202 arr = np.asarray(v, dtype=float) 203 if len(arr) > max_points: 204 idx = np.linspace(0, len(arr) - 1, max_points).astype(int) 205 arr = arr[idx] 206 hist[k] = np.nan_to_num(arr).round(6).tolist() 207 out[nid] = {"calls": rec.calls, "history": hist, 208 "grad_history": {k: np.nan_to_num(np.asarray(v[-max_points:])).round(6).tolist() 209 for k, v in rec.grad_history.items()}, 210 "hist": rec.histogram() if rec.last is not None else None} 211 return out
22class Trace: 23 """Everything recorded during one forward pass.""" 24 25 def __init__(self, net: "Net", args: tuple, kwargs: dict, result): 26 self.net = net 27 self.args, self.kwargs = args, kwargs 28 self.output = result.output 29 self.loss = result.loss 30 self._acts_native = result.acts 31 self.acts: dict[str, np.ndarray] = {k: to_numpy(v) for k, v in result.acts.items() if v is not None} 32 self.inputs: dict[str, np.ndarray] = {k: to_numpy(v) for k, v in result.inputs.items() if v is not None} 33 self.grads: dict[str, np.ndarray] = dict(result.grads) 34 self.param_grads: dict[str, np.ndarray] = dict(result.param_grads) 35 self.attention: dict[str, np.ndarray] = dict(result.attention) 36 self.attention_parts: dict[str, dict] = dict(getattr(result, "attention_parts", {}) or {}) 37 38 def __getitem__(self, node_id: str) -> np.ndarray: 39 if node_id in self.acts: 40 return self.acts[node_id] 41 from ..core.selectors import filter_paths 42 43 m = filter_paths(node_id, list(self.acts)) 44 if len(m) == 1: 45 return self.acts[m[0]] 46 raise KeyError(f"{node_id!r} not recorded; available: {list(self.acts)[:12]}…") 47 48 def __contains__(self, node_id: str) -> bool: 49 return node_id in self.acts 50 51 def keys(self): 52 return self.acts.keys() 53 54 def stats(self, node_id: str, which=DEFAULT_STATS) -> dict[str, float]: 55 return stats(self.acts[node_id], which) 56 57 def table(self, which=("mean", "std", "min", "max", "sparsity")) -> str: 58 g = self.net.graph 59 order = [n for n in g.topo_order() if n in self.acts] 60 head = f"{'node':<32} {'kind':<14} {'shape':<18}" + "".join(f"{w:>10}" for w in which) 61 lines = [head, "─" * len(head)] 62 for nid in order: 63 s = stats(self.acts[nid], which) 64 kind = g.nodes[nid].kind if nid in g.nodes else "" 65 lines.append(f"{nid[:32]:<32} {kind[:14]:<14} {str(self.acts[nid].shape)[:18]:<18}" 66 + "".join(f"{s[w]:>10.4g}" for w in which)) 67 return "\n".join(lines) 68 69 def __repr__(self) -> str: 70 extra = f", grads={len(self.grads)}" if self.grads else "" 71 return f"Trace(nodes={len(self.acts)}{extra})" 72 73 def show(self, **kw): 74 return self.net.show(*self.args, trace=self, **kw)
Everything recorded during one forward pass.
25 def __init__(self, net: "Net", args: tuple, kwargs: dict, result): 26 self.net = net 27 self.args, self.kwargs = args, kwargs 28 self.output = result.output 29 self.loss = result.loss 30 self._acts_native = result.acts 31 self.acts: dict[str, np.ndarray] = {k: to_numpy(v) for k, v in result.acts.items() if v is not None} 32 self.inputs: dict[str, np.ndarray] = {k: to_numpy(v) for k, v in result.inputs.items() if v is not None} 33 self.grads: dict[str, np.ndarray] = dict(result.grads) 34 self.param_grads: dict[str, np.ndarray] = dict(result.param_grads) 35 self.attention: dict[str, np.ndarray] = dict(result.attention) 36 self.attention_parts: dict[str, dict] = dict(getattr(result, "attention_parts", {}) or {})
57 def table(self, which=("mean", "std", "min", "max", "sparsity")) -> str: 58 g = self.net.graph 59 order = [n for n in g.topo_order() if n in self.acts] 60 head = f"{'node':<32} {'kind':<14} {'shape':<18}" + "".join(f"{w:>10}" for w in which) 61 lines = [head, "─" * len(head)] 62 for nid in order: 63 s = stats(self.acts[nid], which) 64 kind = g.nodes[nid].kind if nid in g.nodes else "" 65 lines.append(f"{nid[:32]:<32} {kind[:14]:<14} {str(self.acts[nid].shape)[:18]:<18}" 66 + "".join(f"{s[w]:>10.4g}" for w in which)) 67 return "\n".join(lines)
58class TrainingLog: 59 """Metrics and layer dynamics recorded during training (see the module docstring).""" 60 61 def __init__(self, net: "Net", every: float = 0.0, every_steps: int | None = None, max_snapshots: int = 2000, 62 frames: int = 48, frame_side: int = 16): 63 """When :meth:`record` takes a layer snapshot (metrics are always kept): every ``every_steps`` steps if 64 given, otherwise at most every ``every`` seconds. ``frames`` snapshots (evenly thinned) keep weight 65 pictures and outputs for the page's replay; 0 turns that off.""" 66 self.net = net 67 self.every = float(every) 68 self.every_steps = int(every_steps) if every_steps else None 69 self.max_snapshots = max_snapshots 70 self.steps: list[int] = [] 71 self.metrics: dict[str, list] = {} 72 self.snap_steps: list[int] = [] 73 self.layers: dict[str, dict[str, list]] = {} 74 self._prev: dict[str, np.ndarray] = {} 75 self._last_snap = -1e18 76 self._count = 0 77 self._groups = self._param_groups() 78 self.frames = int(frames) 79 self.frame_side = int(frame_side) 80 self._frames: list[dict] = [] 81 82 def clear(self) -> None: 83 """Forget everything recorded (settings stay): training starts over.""" 84 self.steps, self.metrics, self.snap_steps, self.layers = [], {}, [], {} 85 self._prev, self._frames = {}, [] 86 self._last_snap = -1e18 87 self._count = 0 88 89 # ------------------------------------------------------------------ recording 90 def _param_groups(self) -> dict[str, list[str]]: 91 groups: dict[str, list[str]] = {} 92 self._main: dict[str, str] = {} # each layer's largest parameter: the one replay frames picture 93 seen: set[str] = set() 94 for n in self.net.graph.param_nodes(): 95 infos = [i for i in n.params.values() 96 if i.trainable and i.path not in seen and np.prod(i.shape or (1,)) > 0] 97 if not infos: 98 continue 99 seen.update(i.path for i in infos) 100 groups[n.id] = [i.path for i in infos] 101 self._main[n.id] = max(infos, key=lambda i: int(np.prod(i.shape or (1,)))).path 102 return groups 103 104 def record(self, step: int | None = None, grads=None, trace: "Trace | None" = None, snapshot: bool | None = None, 105 **metrics) -> bool: 106 """Log ``metrics`` for ``step``; also take a layer snapshot if ``every`` seconds passed (or ``snapshot=True``). 107 108 Returns whether a snapshot was taken. 109 """ 110 step = self._count if step is None else int(step) 111 self._count += 1 112 if metrics or not self.steps or step != self.steps[-1]: # a bare refresh of the same step logs nothing new 113 self.log(step, **metrics) 114 if (snapshot or (snapshot is None and self.due(step))) and not (self.snap_steps and step == self.snap_steps[-1]): 115 self.snapshot(step, grads=grads, trace=trace) 116 return True 117 return False 118 119 def due(self, step: int) -> bool: 120 """Whether a layer snapshot is due at ``step`` under this log's schedule.""" 121 if self.every_steps: 122 return not self.snap_steps or step - self.snap_steps[-1] >= self.every_steps 123 return (time.monotonic() - self._last_snap) >= self.every 124 125 def log(self, step: int, **metrics) -> None: 126 """Scalars only (cheap): ``log(step, loss=0.3, acc=0.9)``. Logging the latest step again adds to it.""" 127 step = int(step) 128 if not self.steps or step != self.steps[-1]: 129 self.steps.append(step) 130 n = len(self.steps) 131 for k, v in metrics.items(): 132 try: 133 val = float(v.item() if hasattr(v, "item") else v) 134 except (TypeError, ValueError): 135 continue 136 series = self.metrics.setdefault(k, []) 137 series.extend([None] * (n - len(series))) 138 series[-1] = val 139 for series in self.metrics.values(): 140 series.extend([None] * (n - len(series))) 141 142 def snapshot(self, step: int | None = None, grads=None, trace: "Trace | None" = None) -> None: 143 """Per-layer ‖θ‖, relative update since the last snapshot, ‖∇θ‖ and output spread.""" 144 b = self.net.backend 145 step = (self.steps[-1] if self.steps else 0) if step is None else int(step) 146 g = b.grads(grads) 147 first = not self.snap_steps 148 gap = max(1, step - self.snap_steps[-1]) if self.snap_steps else 1 149 self.snap_steps.append(step) 150 for nid, paths in self._groups.items(): 151 rec = self.layers.setdefault(nid, {k: [] for k in LAYER_STATS}) 152 sq = dsq = psq = gsq = 0.0 153 has_grad = False 154 for p in paths: 155 w = b.get_param(p).astype(np.float64, copy=False) 156 sq += float(np.sum(w * w)) 157 prev = self._prev.get(p) 158 if prev is not None and prev.shape == w.shape: 159 d = w - prev 160 dsq += float(np.sum(d * d)) 161 psq += float(np.sum(prev * prev)) 162 self._prev[p] = w.astype(np.float32) 163 if p in g: 164 has_grad = True 165 gg = np.asarray(g[p], dtype=np.float64) 166 gsq += float(np.sum(gg * gg)) 167 rec["norm"].append(_finite(math.sqrt(sq))) 168 rec["update"].append(None if first or psq == 0 else _finite(math.sqrt(dsq) / math.sqrt(psq) / gap)) 169 rec["grad"].append(_finite(math.sqrt(gsq)) if has_grad else None) 170 a = trace.acts.get(nid) if trace is not None else None 171 rec["act"].append(_finite(np.std(a)) if a is not None and np.size(a) else None) 172 self._last_snap = time.monotonic() 173 if self.frames > 0: 174 self._keep_frame(step, trace) 175 if len(self.snap_steps) > self.max_snapshots: # thin out the older half 176 keep = list(range(0, len(self.snap_steps) // 2, 2)) + list(range(len(self.snap_steps) // 2, 177 len(self.snap_steps))) 178 self.snap_steps = [self.snap_steps[i] for i in keep] 179 for rec in self.layers.values(): 180 for k in rec: 181 rec[k] = [rec[k][i] for i in keep] 182 183 def _keep_frame(self, step: int, trace) -> None: 184 """A small picture of every layer's main weight, and the output, for the replay slider.""" 185 from ..core.tensor import first_array, to_numpy 186 from ..viz.html.payload import heat 187 188 b = self.net.backend 189 weights = {} 190 for nid in self._groups: 191 w = np.asarray(b.get_param(self._main[nid]), dtype=np.float64) 192 w2 = w.reshape(1, -1) if w.ndim < 2 else w.reshape(w.shape[0], -1) 193 weights[nid] = heat(w2, True, self.frame_side, quantize=True) 194 out = None 195 if trace is not None and trace.output is not None: 196 a = first_array(trace.output) 197 if a is not None: 198 a = to_numpy(a) 199 out = a.astype(np.float32) if a.size <= 200_000 else None 200 self._frames.append({"step": int(step), "weights": weights, "output": out}) 201 if len(self._frames) > 2 * self.frames: # keep the first, thin the rest evenly 202 self._frames = self._frames[:1] + self._frames[2::2] 203 204 def frame_list(self, labels=None, tokenizer=None, sample: int = 0) -> list[dict]: 205 """The kept frames, at most ``frames`` of them evenly spaced, as page payload.""" 206 if not self._frames: 207 return [] 208 from ..viz.html.payload import _output_payload 209 210 idx = np.unique(np.linspace(0, len(self._frames) - 1, min(self.frames, len(self._frames))).round().astype(int)) 211 out = [] 212 for i in idx: 213 f = self._frames[int(i)] 214 o = None 215 if f["output"] is not None: 216 try: 217 o = _output_payload(f["output"], None, sample, labels, tokenizer) 218 except Exception: # noqa: BLE001 - an output we can't draw: the weights still replay 219 o = None 220 out.append({"step": f["step"], "weights": f["weights"], "output": o}) 221 return out 222 223 # ------------------------------------------------------------------ export 224 def __len__(self) -> int: 225 return len(self.steps) 226 227 @property 228 def last_step(self) -> int | None: 229 return self.steps[-1] if self.steps else None 230 231 def history(self, name: str) -> tuple[np.ndarray, np.ndarray]: 232 """``(steps, values)`` of a metric, or of a layer stat as ``"<node>:<stat>"``.""" 233 if name in self.metrics: 234 return np.asarray(self.steps), np.array([np.nan if v is None else v for v in self.metrics[name]]) 235 nid, _, stat = name.rpartition(":") 236 vals = self.layers[nid][stat] 237 return np.asarray(self.snap_steps), np.array([np.nan if v is None else v for v in vals]) 238 239 def to_dict(self, max_points: int = 600, max_snapshots: int = 240, labels=None, tokenizer=None, 240 sample: int = 0) -> dict: 241 m_steps = _bucket(self.steps, [0.0] * len(self.steps), max_points)[0] 242 metrics = {k: _bucket(self.steps, v, max_points)[1] for k, v in self.metrics.items()} 243 s_steps = _bucket(self.snap_steps, [0.0] * len(self.snap_steps), max_snapshots)[0] 244 g = self.net.graph 245 layers = [] 246 for nid, rec in self.layers.items(): 247 n = g.nodes.get(nid) 248 stats = {k: _bucket(self.snap_steps, vals, max_snapshots)[1] for k, vals in rec.items() 249 if any(x is not None for x in vals)} 250 layers.append({"id": nid, "kind": n.kind if n else "", "stats": stats}) 251 return {"steps": m_steps, "metrics": metrics, "snapSteps": s_steps, "layers": layers, 252 "lastStep": self.last_step, "count": len(self.steps), 253 "frames": self.frame_list(labels, tokenizer, sample)} 254 255 def __repr__(self) -> str: 256 last = {k: v[-1] for k, v in self.metrics.items() if v and v[-1] is not None} 257 return (f"TrainingLog(steps={len(self.steps)}, snapshots={len(self.snap_steps)}, " 258 f"last={ {k: round(v, 4) for k, v in last.items()} })")
Metrics and layer dynamics recorded during training (see the module docstring).
61 def __init__(self, net: "Net", every: float = 0.0, every_steps: int | None = None, max_snapshots: int = 2000, 62 frames: int = 48, frame_side: int = 16): 63 """When :meth:`record` takes a layer snapshot (metrics are always kept): every ``every_steps`` steps if 64 given, otherwise at most every ``every`` seconds. ``frames`` snapshots (evenly thinned) keep weight 65 pictures and outputs for the page's replay; 0 turns that off.""" 66 self.net = net 67 self.every = float(every) 68 self.every_steps = int(every_steps) if every_steps else None 69 self.max_snapshots = max_snapshots 70 self.steps: list[int] = [] 71 self.metrics: dict[str, list] = {} 72 self.snap_steps: list[int] = [] 73 self.layers: dict[str, dict[str, list]] = {} 74 self._prev: dict[str, np.ndarray] = {} 75 self._last_snap = -1e18 76 self._count = 0 77 self._groups = self._param_groups() 78 self.frames = int(frames) 79 self.frame_side = int(frame_side) 80 self._frames: list[dict] = []
When record() takes a layer snapshot (metrics are always kept): every every_steps steps if
given, otherwise at most every every seconds. frames snapshots (evenly thinned) keep weight
pictures and outputs for the page's replay; 0 turns that off.
82 def clear(self) -> None: 83 """Forget everything recorded (settings stay): training starts over.""" 84 self.steps, self.metrics, self.snap_steps, self.layers = [], {}, [], {} 85 self._prev, self._frames = {}, [] 86 self._last_snap = -1e18 87 self._count = 0
Forget everything recorded (settings stay): training starts over.
104 def record(self, step: int | None = None, grads=None, trace: "Trace | None" = None, snapshot: bool | None = None, 105 **metrics) -> bool: 106 """Log ``metrics`` for ``step``; also take a layer snapshot if ``every`` seconds passed (or ``snapshot=True``). 107 108 Returns whether a snapshot was taken. 109 """ 110 step = self._count if step is None else int(step) 111 self._count += 1 112 if metrics or not self.steps or step != self.steps[-1]: # a bare refresh of the same step logs nothing new 113 self.log(step, **metrics) 114 if (snapshot or (snapshot is None and self.due(step))) and not (self.snap_steps and step == self.snap_steps[-1]): 115 self.snapshot(step, grads=grads, trace=trace) 116 return True 117 return False
119 def due(self, step: int) -> bool: 120 """Whether a layer snapshot is due at ``step`` under this log's schedule.""" 121 if self.every_steps: 122 return not self.snap_steps or step - self.snap_steps[-1] >= self.every_steps 123 return (time.monotonic() - self._last_snap) >= self.every
Whether a layer snapshot is due at step under this log's schedule.
125 def log(self, step: int, **metrics) -> None: 126 """Scalars only (cheap): ``log(step, loss=0.3, acc=0.9)``. Logging the latest step again adds to it.""" 127 step = int(step) 128 if not self.steps or step != self.steps[-1]: 129 self.steps.append(step) 130 n = len(self.steps) 131 for k, v in metrics.items(): 132 try: 133 val = float(v.item() if hasattr(v, "item") else v) 134 except (TypeError, ValueError): 135 continue 136 series = self.metrics.setdefault(k, []) 137 series.extend([None] * (n - len(series))) 138 series[-1] = val 139 for series in self.metrics.values(): 140 series.extend([None] * (n - len(series)))
Scalars only (cheap): log(step, loss=0.3, acc=0.9). Logging the latest step again adds to it.
142 def snapshot(self, step: int | None = None, grads=None, trace: "Trace | None" = None) -> None: 143 """Per-layer ‖θ‖, relative update since the last snapshot, ‖∇θ‖ and output spread.""" 144 b = self.net.backend 145 step = (self.steps[-1] if self.steps else 0) if step is None else int(step) 146 g = b.grads(grads) 147 first = not self.snap_steps 148 gap = max(1, step - self.snap_steps[-1]) if self.snap_steps else 1 149 self.snap_steps.append(step) 150 for nid, paths in self._groups.items(): 151 rec = self.layers.setdefault(nid, {k: [] for k in LAYER_STATS}) 152 sq = dsq = psq = gsq = 0.0 153 has_grad = False 154 for p in paths: 155 w = b.get_param(p).astype(np.float64, copy=False) 156 sq += float(np.sum(w * w)) 157 prev = self._prev.get(p) 158 if prev is not None and prev.shape == w.shape: 159 d = w - prev 160 dsq += float(np.sum(d * d)) 161 psq += float(np.sum(prev * prev)) 162 self._prev[p] = w.astype(np.float32) 163 if p in g: 164 has_grad = True 165 gg = np.asarray(g[p], dtype=np.float64) 166 gsq += float(np.sum(gg * gg)) 167 rec["norm"].append(_finite(math.sqrt(sq))) 168 rec["update"].append(None if first or psq == 0 else _finite(math.sqrt(dsq) / math.sqrt(psq) / gap)) 169 rec["grad"].append(_finite(math.sqrt(gsq)) if has_grad else None) 170 a = trace.acts.get(nid) if trace is not None else None 171 rec["act"].append(_finite(np.std(a)) if a is not None and np.size(a) else None) 172 self._last_snap = time.monotonic() 173 if self.frames > 0: 174 self._keep_frame(step, trace) 175 if len(self.snap_steps) > self.max_snapshots: # thin out the older half 176 keep = list(range(0, len(self.snap_steps) // 2, 2)) + list(range(len(self.snap_steps) // 2, 177 len(self.snap_steps))) 178 self.snap_steps = [self.snap_steps[i] for i in keep] 179 for rec in self.layers.values(): 180 for k in rec: 181 rec[k] = [rec[k][i] for i in keep]
Per-layer ‖θ‖, relative update since the last snapshot, ‖∇θ‖ and output spread.
204 def frame_list(self, labels=None, tokenizer=None, sample: int = 0) -> list[dict]: 205 """The kept frames, at most ``frames`` of them evenly spaced, as page payload.""" 206 if not self._frames: 207 return [] 208 from ..viz.html.payload import _output_payload 209 210 idx = np.unique(np.linspace(0, len(self._frames) - 1, min(self.frames, len(self._frames))).round().astype(int)) 211 out = [] 212 for i in idx: 213 f = self._frames[int(i)] 214 o = None 215 if f["output"] is not None: 216 try: 217 o = _output_payload(f["output"], None, sample, labels, tokenizer) 218 except Exception: # noqa: BLE001 - an output we can't draw: the weights still replay 219 o = None 220 out.append({"step": f["step"], "weights": f["weights"], "output": o}) 221 return out
The kept frames, at most frames of them evenly spaced, as page payload.
231 def history(self, name: str) -> tuple[np.ndarray, np.ndarray]: 232 """``(steps, values)`` of a metric, or of a layer stat as ``"<node>:<stat>"``.""" 233 if name in self.metrics: 234 return np.asarray(self.steps), np.array([np.nan if v is None else v for v in self.metrics[name]]) 235 nid, _, stat = name.rpartition(":") 236 vals = self.layers[nid][stat] 237 return np.asarray(self.snap_steps), np.array([np.nan if v is None else v for v in vals])
(steps, values) of a metric, or of a layer stat as "<node>:<stat>".
239 def to_dict(self, max_points: int = 600, max_snapshots: int = 240, labels=None, tokenizer=None, 240 sample: int = 0) -> dict: 241 m_steps = _bucket(self.steps, [0.0] * len(self.steps), max_points)[0] 242 metrics = {k: _bucket(self.steps, v, max_points)[1] for k, v in self.metrics.items()} 243 s_steps = _bucket(self.snap_steps, [0.0] * len(self.snap_steps), max_snapshots)[0] 244 g = self.net.graph 245 layers = [] 246 for nid, rec in self.layers.items(): 247 n = g.nodes.get(nid) 248 stats = {k: _bucket(self.snap_steps, vals, max_snapshots)[1] for k, vals in rec.items() 249 if any(x is not None for x in vals)} 250 layers.append({"id": nid, "kind": n.kind if n else "", "stats": stats}) 251 return {"steps": m_steps, "metrics": metrics, "snapSteps": s_steps, "layers": layers, 252 "lastStep": self.last_step, "count": len(self.steps), 253 "frames": self.frame_list(labels, tokenizer, sample)}
124class ModelGraph: 125 def __init__(self, name: str = "model", framework: str = ""): 126 self.name = name 127 self.framework = framework 128 self.nodes: dict[str, Node] = {} 129 self.edges: list[Edge] = [] 130 self._edge_keys: set[tuple[str, str]] = set() 131 self._cache: dict = {} # topological order, adjacency — rebuilt when nodes or edges change 132 133 # ----------------------------------------------------------------- caching 134 def _cached(self, name: str, build): 135 """``build()`` once per state of the graph: big graphs ask for their order and neighbours thousands of times 136 (one equation per layer), and recomputing them each time is quadratic.""" 137 key = (id(self.nodes), len(self.nodes), id(self.edges), len(self.edges)) 138 c = self.__dict__.get("_cache") 139 if c is None or c.get("_key") != key: 140 c = self._cache = {"_key": key} 141 if name not in c: 142 c[name] = build() 143 return c[name] 144 145 def changed(self) -> None: 146 """Forget the cached order and neighbours (after changing a node's ``op`` in place).""" 147 self._cache = {} 148 149 def _adjacency(self) -> tuple[dict, dict]: 150 def build(): 151 succ: dict[str, list[str]] = {} 152 pred: dict[str, list[str]] = {} 153 for e in self.edges: 154 succ.setdefault(e.src, []).append(e.dst) 155 pred.setdefault(e.dst, []).append(e.src) 156 return succ, pred 157 return self._cached("adjacency", build) 158 159 # ------------------------------------------------------------------ build 160 def add_node(self, node: Node) -> Node: 161 if node.id in self.nodes: 162 raise ValueError(f"duplicate node id {node.id!r}") 163 self.nodes[node.id] = node 164 if node.parent is not None and node.parent in self.nodes: 165 par = self.nodes[node.parent] 166 if node.id not in par.children: 167 par.children.append(node.id) 168 return node 169 170 def add_edge(self, src: str, dst: str, shape=None, implicit: bool = False) -> None: 171 if src == dst or (src, dst) in self._edge_keys: 172 return 173 self._edge_keys.add((src, dst)) 174 self.edges.append(Edge(src, dst, tuple(shape) if shape is not None else None, implicit)) 175 176 def link_children(self) -> None: 177 """(Re)build ``children`` lists from ``parent`` pointers, preserving insertion order.""" 178 for n in self.nodes.values(): 179 n.children = [] 180 for n in self.nodes.values(): 181 if n.parent is not None and n.parent in self.nodes and n.parent != n.id: 182 self.nodes[n.parent].children.append(n.id) 183 184 # ----------------------------------------------------------------- queries 185 def __getitem__(self, key: str) -> Node: 186 return self.nodes[key] 187 188 def __contains__(self, key: str) -> bool: 189 return key in self.nodes 190 191 def __len__(self) -> int: 192 return len(self.nodes) 193 194 @property 195 def root(self) -> Node | None: 196 return self.nodes.get("") 197 198 def compute_nodes(self) -> list[Node]: 199 return [n for n in self.nodes.values() if n.is_compute] 200 201 def containers(self) -> list[Node]: 202 return [n for n in self.nodes.values() if n.is_container] 203 204 def inputs(self) -> list[Node]: 205 return [n for n in self.nodes.values() if n.op == "input"] 206 207 def outputs(self) -> list[Node]: 208 return [n for n in self.nodes.values() if n.op == "output"] 209 210 def succ(self, nid: str) -> list[str]: 211 return list(self._adjacency()[0].get(nid, ())) 212 213 def pred(self, nid: str) -> list[str]: 214 return list(self._adjacency()[1].get(nid, ())) 215 216 def ancestors(self, nid: str) -> list[str]: 217 out, cur = [], self.nodes[nid].parent 218 while cur is not None and cur in self.nodes: 219 out.append(cur) 220 nxt = self.nodes[cur].parent 221 if nxt == cur: 222 break 223 cur = nxt 224 return out 225 226 def depth(self, nid: str) -> int: 227 return len([a for a in self.ancestors(nid) if a != ""]) 228 229 def descendants(self, nid: str) -> list[str]: 230 out, stack = [], list(self.nodes[nid].children) 231 while stack: 232 c = stack.pop(0) 233 out.append(c) 234 stack.extend(self.nodes[c].children) 235 return out 236 237 def in_subtree(self, nid: str, root: str) -> bool: 238 return nid == root or root == "" or root in self.ancestors(nid) 239 240 def topo_order(self) -> list[str]: 241 """Topological order of compute nodes (insertion order breaks ties).""" 242 return list(self._cached("topo", self._topo_order)) 243 244 def _topo_order(self) -> list[str]: 245 import heapq 246 247 ids = [n.id for n in self.compute_nodes()] 248 index = {k: i for i, k in enumerate(ids)} 249 indeg = {k: 0 for k in ids} 250 adj: dict[str, list[str]] = {k: [] for k in ids} 251 for e in self.edges: 252 if e.src in indeg and e.dst in indeg: 253 adj[e.src].append(e.dst) 254 indeg[e.dst] += 1 255 ready = [(index[k], k) for k in ids if indeg[k] == 0] # a heap on insertion order: ties stay stable 256 heapq.heapify(ready) 257 order = [] 258 while ready: 259 _, k = heapq.heappop(ready) 260 order.append(k) 261 for d in adj[k]: 262 indeg[d] -= 1 263 if indeg[d] == 0: 264 heapq.heappush(ready, (index[d], d)) 265 if len(order) < len(ids): # cycle: fall back to insertion order for the rest 266 done = set(order) 267 order += [k for k in ids if k not in done] 268 return order 269 270 def param_nodes(self) -> list[Node]: 271 """Compute nodes that own parameters, in topological order.""" 272 return [self.nodes[k] for k in self.topo_order() if self.nodes[k].params] 273 274 def max_depth(self) -> int: 275 return max((self.depth(n.id) for n in self.nodes.values() if n.is_compute), default=0) 276 277 # --------------------------------------------------------- transformations 278 def collapse(self, depth: int) -> "ModelGraph": 279 """Return a graph where containers at ``depth`` become opaque compute nodes. 280 281 depth=0 keeps only the top-level children of the root; every descendant of a 282 collapsed container is folded into it and edges are re-routed. 283 """ 284 rep: dict[str, str] = {} 285 for n in self.nodes.values(): 286 if not n.is_compute: 287 continue 288 chain = [a for a in reversed(self.ancestors(n.id)) if a != ""] # outermost first 289 target = n.id 290 if len(chain) > depth: 291 target = chain[depth] 292 rep[n.id] = target 293 294 g = ModelGraph(self.name, self.framework) 295 keep_containers = {a for n in self.nodes.values() for a in self.ancestors(n.id)} 296 for n in self.nodes.values(): 297 if n.is_compute and rep.get(n.id) == n.id: 298 g.add_node(_copy_node(n)) 299 elif n.is_container and n.id in set(rep.values()): 300 c = _copy_node(n) 301 c.op = "module" 302 c.attrs = dict(c.attrs, collapsed=True) 303 members = [m for m, r in rep.items() if r == n.id] 304 if members and all(self.nodes[m].attrs.get("unused") for m in members): 305 c.attrs["unused"] = True 306 c.params = {} 307 for m in members: 308 for p in self.nodes[m].params.values(): 309 c.params[p.path[len(n.id) + 1:] if n.id else p.path] = p 310 ins = [e for e in self.edges if rep.get(e.dst) == n.id and rep.get(e.src) != n.id] 311 outs = [e for e in self.edges if rep.get(e.src) == n.id and rep.get(e.dst) != n.id] 312 if ins: 313 c.in_shapes = [self.nodes[ins[0].dst].in_shapes[0]] if self.nodes[ins[0].dst].in_shapes else [] 314 if outs: 315 c.out_shapes = self.nodes[outs[-1].src].out_shapes 316 g.add_node(c) 317 elif n.is_container and n.id in keep_containers: 318 g.add_node(_copy_node(n)) 319 g.link_children() 320 for e in self.edges: 321 s, d = rep.get(e.src, e.src), rep.get(e.dst, e.dst) 322 if s in g.nodes and d in g.nodes: 323 g.add_edge(s, d, e.shape, e.implicit) 324 return g 325 326 def subgraph(self, root: str) -> "ModelGraph": 327 """Nodes inside ``root``'s subtree plus boundary input/output stubs.""" 328 if root == "": 329 return self 330 g = ModelGraph(f"{self.name}.{root}", self.framework) 331 inside = {n.id for n in self.nodes.values() if self.in_subtree(n.id, root)} 332 for n in self.nodes.values(): 333 if n.id in inside: 334 c = _copy_node(n) 335 if n.id == root: 336 c.parent = None 337 g.add_node(c) 338 g.link_children() 339 in_stub, out_stub = f"@in:{root}", f"@out:{root}" 340 for e in self.edges: 341 si, di = e.src in inside, e.dst in inside 342 if si and di: 343 g.add_edge(e.src, e.dst, e.shape, e.implicit) 344 elif di and not si: 345 if in_stub not in g.nodes: 346 g.add_node(Node(in_stub, "Input", "Input", "input", parent=root, 347 out_shapes=[e.shape] if e.shape else [], label="z")) 348 g.add_edge(in_stub, e.dst, e.shape) 349 elif si and not di: 350 if out_stub not in g.nodes: 351 g.add_node(Node(out_stub, "Output", "Output", "output", parent=root, 352 in_shapes=[e.shape] if e.shape else [], label="out")) 353 g.add_edge(e.src, out_stub, e.shape) 354 g.link_children() 355 return g 356 357 # ----------------------------------------------------------------- export 358 def to_dict(self) -> dict: 359 return { 360 "name": self.name, 361 "framework": self.framework, 362 "nodes": [n.to_dict() for n in self.nodes.values()], 363 "edges": [{"src": e.src, "dst": e.dst, "shape": list(e.shape) if e.shape else None, 364 "implicit": e.implicit} for e in self.edges], 365 } 366 367 def summary(self, max_rows: int = 200) -> str: 368 rows = [("path", "kind", "output shape", "#params")] 369 total = 0 370 seen: set[str] = set() 371 372 def walk(nid: str, indent: int): 373 nonlocal total 374 n = self.nodes[nid] 375 if n.op in ("input", "output"): 376 return 377 base = (n.label or n.id.split(".")[-1]) if n.op in ("module", "container") else n.id.split(".")[-1] 378 name = (" " * indent) + (base if n.id else self.name) 379 shape = n.out_shapes[0] if n.out_shapes else "" 380 own = n.n_params 381 fresh = [p for p in n.params.values() if p.trainable and p.path not in seen] 382 seen.update(p.path for p in fresh) 383 total += sum(p.numel for p in fresh) # tied / shared parameters count once 384 np_str = f"{own:,}" if n.is_compute and own else "" 385 if n.is_container: 386 sub = sum(self.nodes[d].n_params for d in self.descendants(nid) if self.nodes[d].is_compute) 387 np_str = f"({sub:,})" 388 rows.append((name, n.kind if n.is_compute else n.type_name, str(tuple(shape)) if shape else "", np_str)) 389 for c in n.children: 390 walk(c, indent + 1) 391 392 if "" in self.nodes: 393 walk("", 0) 394 else: 395 for n in self.compute_nodes(): 396 walk(n.id, 0) 397 rows = rows[: max_rows + 1] 398 widths = [max(len(r[i]) for r in rows) for i in range(4)] 399 line = "─" * (sum(widths) + 9) 400 out = [line, " │ ".join(r.ljust(w) for r, w in zip(rows[0], widths)), line] 401 out += [" │ ".join(r.ljust(w) for r, w in zip(row, widths)) for row in rows[1:]] 402 out += [line, f"total parameters: {total:,}", line] 403 return "\n".join(out) 404 405 def __repr__(self) -> str: 406 return (f"ModelGraph({self.name!r}, framework={self.framework!r}, " 407 f"nodes={len(self.nodes)}, edges={len(self.edges)})")
125 def __init__(self, name: str = "model", framework: str = ""): 126 self.name = name 127 self.framework = framework 128 self.nodes: dict[str, Node] = {} 129 self.edges: list[Edge] = [] 130 self._edge_keys: set[tuple[str, str]] = set() 131 self._cache: dict = {} # topological order, adjacency — rebuilt when nodes or edges change
145 def changed(self) -> None: 146 """Forget the cached order and neighbours (after changing a node's ``op`` in place).""" 147 self._cache = {}
Forget the cached order and neighbours (after changing a node's op in place).
160 def add_node(self, node: Node) -> Node: 161 if node.id in self.nodes: 162 raise ValueError(f"duplicate node id {node.id!r}") 163 self.nodes[node.id] = node 164 if node.parent is not None and node.parent in self.nodes: 165 par = self.nodes[node.parent] 166 if node.id not in par.children: 167 par.children.append(node.id) 168 return node
176 def link_children(self) -> None: 177 """(Re)build ``children`` lists from ``parent`` pointers, preserving insertion order.""" 178 for n in self.nodes.values(): 179 n.children = [] 180 for n in self.nodes.values(): 181 if n.parent is not None and n.parent in self.nodes and n.parent != n.id: 182 self.nodes[n.parent].children.append(n.id)
(Re)build children lists from parent pointers, preserving insertion order.
240 def topo_order(self) -> list[str]: 241 """Topological order of compute nodes (insertion order breaks ties).""" 242 return list(self._cached("topo", self._topo_order))
Topological order of compute nodes (insertion order breaks ties).
270 def param_nodes(self) -> list[Node]: 271 """Compute nodes that own parameters, in topological order.""" 272 return [self.nodes[k] for k in self.topo_order() if self.nodes[k].params]
Compute nodes that own parameters, in topological order.
278 def collapse(self, depth: int) -> "ModelGraph": 279 """Return a graph where containers at ``depth`` become opaque compute nodes. 280 281 depth=0 keeps only the top-level children of the root; every descendant of a 282 collapsed container is folded into it and edges are re-routed. 283 """ 284 rep: dict[str, str] = {} 285 for n in self.nodes.values(): 286 if not n.is_compute: 287 continue 288 chain = [a for a in reversed(self.ancestors(n.id)) if a != ""] # outermost first 289 target = n.id 290 if len(chain) > depth: 291 target = chain[depth] 292 rep[n.id] = target 293 294 g = ModelGraph(self.name, self.framework) 295 keep_containers = {a for n in self.nodes.values() for a in self.ancestors(n.id)} 296 for n in self.nodes.values(): 297 if n.is_compute and rep.get(n.id) == n.id: 298 g.add_node(_copy_node(n)) 299 elif n.is_container and n.id in set(rep.values()): 300 c = _copy_node(n) 301 c.op = "module" 302 c.attrs = dict(c.attrs, collapsed=True) 303 members = [m for m, r in rep.items() if r == n.id] 304 if members and all(self.nodes[m].attrs.get("unused") for m in members): 305 c.attrs["unused"] = True 306 c.params = {} 307 for m in members: 308 for p in self.nodes[m].params.values(): 309 c.params[p.path[len(n.id) + 1:] if n.id else p.path] = p 310 ins = [e for e in self.edges if rep.get(e.dst) == n.id and rep.get(e.src) != n.id] 311 outs = [e for e in self.edges if rep.get(e.src) == n.id and rep.get(e.dst) != n.id] 312 if ins: 313 c.in_shapes = [self.nodes[ins[0].dst].in_shapes[0]] if self.nodes[ins[0].dst].in_shapes else [] 314 if outs: 315 c.out_shapes = self.nodes[outs[-1].src].out_shapes 316 g.add_node(c) 317 elif n.is_container and n.id in keep_containers: 318 g.add_node(_copy_node(n)) 319 g.link_children() 320 for e in self.edges: 321 s, d = rep.get(e.src, e.src), rep.get(e.dst, e.dst) 322 if s in g.nodes and d in g.nodes: 323 g.add_edge(s, d, e.shape, e.implicit) 324 return g
Return a graph where containers at depth become opaque compute nodes.
depth=0 keeps only the top-level children of the root; every descendant of a collapsed container is folded into it and edges are re-routed.
326 def subgraph(self, root: str) -> "ModelGraph": 327 """Nodes inside ``root``'s subtree plus boundary input/output stubs.""" 328 if root == "": 329 return self 330 g = ModelGraph(f"{self.name}.{root}", self.framework) 331 inside = {n.id for n in self.nodes.values() if self.in_subtree(n.id, root)} 332 for n in self.nodes.values(): 333 if n.id in inside: 334 c = _copy_node(n) 335 if n.id == root: 336 c.parent = None 337 g.add_node(c) 338 g.link_children() 339 in_stub, out_stub = f"@in:{root}", f"@out:{root}" 340 for e in self.edges: 341 si, di = e.src in inside, e.dst in inside 342 if si and di: 343 g.add_edge(e.src, e.dst, e.shape, e.implicit) 344 elif di and not si: 345 if in_stub not in g.nodes: 346 g.add_node(Node(in_stub, "Input", "Input", "input", parent=root, 347 out_shapes=[e.shape] if e.shape else [], label="z")) 348 g.add_edge(in_stub, e.dst, e.shape) 349 elif si and not di: 350 if out_stub not in g.nodes: 351 g.add_node(Node(out_stub, "Output", "Output", "output", parent=root, 352 in_shapes=[e.shape] if e.shape else [], label="out")) 353 g.add_edge(e.src, out_stub, e.shape) 354 g.link_children() 355 return g
Nodes inside root's subtree plus boundary input/output stubs.
358 def to_dict(self) -> dict: 359 return { 360 "name": self.name, 361 "framework": self.framework, 362 "nodes": [n.to_dict() for n in self.nodes.values()], 363 "edges": [{"src": e.src, "dst": e.dst, "shape": list(e.shape) if e.shape else None, 364 "implicit": e.implicit} for e in self.edges], 365 }
367 def summary(self, max_rows: int = 200) -> str: 368 rows = [("path", "kind", "output shape", "#params")] 369 total = 0 370 seen: set[str] = set() 371 372 def walk(nid: str, indent: int): 373 nonlocal total 374 n = self.nodes[nid] 375 if n.op in ("input", "output"): 376 return 377 base = (n.label or n.id.split(".")[-1]) if n.op in ("module", "container") else n.id.split(".")[-1] 378 name = (" " * indent) + (base if n.id else self.name) 379 shape = n.out_shapes[0] if n.out_shapes else "" 380 own = n.n_params 381 fresh = [p for p in n.params.values() if p.trainable and p.path not in seen] 382 seen.update(p.path for p in fresh) 383 total += sum(p.numel for p in fresh) # tied / shared parameters count once 384 np_str = f"{own:,}" if n.is_compute and own else "" 385 if n.is_container: 386 sub = sum(self.nodes[d].n_params for d in self.descendants(nid) if self.nodes[d].is_compute) 387 np_str = f"({sub:,})" 388 rows.append((name, n.kind if n.is_compute else n.type_name, str(tuple(shape)) if shape else "", np_str)) 389 for c in n.children: 390 walk(c, indent + 1) 391 392 if "" in self.nodes: 393 walk("", 0) 394 else: 395 for n in self.compute_nodes(): 396 walk(n.id, 0) 397 rows = rows[: max_rows + 1] 398 widths = [max(len(r[i]) for r in rows) for i in range(4)] 399 line = "─" * (sum(widths) + 9) 400 out = [line, " │ ".join(r.ljust(w) for r, w in zip(rows[0], widths)), line] 401 out += [" │ ".join(r.ljust(w) for r, w in zip(row, widths)) for row in rows[1:]] 402 out += [line, f"total parameters: {total:,}", line] 403 return "\n".join(out)
39@dataclass 40class Node: 41 id: str 42 kind: str 43 type_name: str 44 op: str # input | module | function | param | output | container 45 parent: str | None = None 46 children: list[str] = field(default_factory=list) 47 params: dict[str, ParamInfo] = field(default_factory=dict) 48 roles: dict[str, Role] = field(default_factory=dict) 49 attrs: dict[str, Any] = field(default_factory=dict) 50 in_shapes: list = field(default_factory=list) 51 out_shapes: list = field(default_factory=list) 52 module: str | None = None # module whose weights this call uses (weight sharing) 53 label: str | None = None 54 55 @property 56 def is_container(self) -> bool: 57 return self.op == "container" 58 59 @property 60 def is_compute(self) -> bool: 61 return self.op in COMPUTE_OPS 62 63 @property 64 def n_params(self) -> int: 65 """Trainable parameters (buffers such as BatchNorm running statistics are not counted).""" 66 return sum(p.numel for p in self.params.values() if p.trainable) 67 68 @property 69 def display(self) -> str: 70 return self.label or self.id or "<root>" 71 72 def role_param(self, role: str) -> ParamInfo | None: 73 r = self.roles.get(role) 74 return self.params.get(r.name) if r else None 75 76 def to_dict(self) -> dict: 77 return { 78 "id": self.id, 79 "kind": self.kind, 80 "type": self.type_name, 81 "op": self.op, 82 "parent": self.parent, 83 "children": list(self.children), 84 "label": self.display, 85 "module": self.module, 86 "params": [ 87 {"name": p.name, "path": p.path, "shape": list(p.shape), "dtype": p.dtype, 88 "numel": p.numel, "trainable": p.trainable} 89 for p in self.params.values() 90 ], 91 "roles": {k: {"name": r.name, "out_axis": r.out_axis, "in_axis": r.in_axis} 92 for k, r in self.roles.items()}, 93 "attrs": _jsonable(self.attrs), 94 "in_shapes": [list(s) if s is not None else None for s in self.in_shapes], 95 "out_shapes": [list(s) if s is not None else None for s in self.out_shapes], 96 }
63 @property 64 def n_params(self) -> int: 65 """Trainable parameters (buffers such as BatchNorm running statistics are not counted).""" 66 return sum(p.numel for p in self.params.values() if p.trainable)
Trainable parameters (buffers such as BatchNorm running statistics are not counted).
76 def to_dict(self) -> dict: 77 return { 78 "id": self.id, 79 "kind": self.kind, 80 "type": self.type_name, 81 "op": self.op, 82 "parent": self.parent, 83 "children": list(self.children), 84 "label": self.display, 85 "module": self.module, 86 "params": [ 87 {"name": p.name, "path": p.path, "shape": list(p.shape), "dtype": p.dtype, 88 "numel": p.numel, "trainable": p.trainable} 89 for p in self.params.values() 90 ], 91 "roles": {k: {"name": r.name, "out_axis": r.out_axis, "in_axis": r.in_axis} 92 for k, r in self.roles.items()}, 93 "attrs": _jsonable(self.attrs), 94 "in_shapes": [list(s) if s is not None else None for s in self.in_shapes], 95 "out_shapes": [list(s) if s is not None else None for s in self.out_shapes], 96 }
22@dataclass 23class ParamInfo: 24 path: str # global path, e.g. "blocks.0.fc.weight" 25 name: str # local name, e.g. "weight" 26 module: str # owning module path 27 shape: tuple 28 dtype: str 29 trainable: bool = True 30 31 @property 32 def numel(self) -> int: 33 n = 1 34 for s in self.shape: 35 n *= int(s) 36 return n
30@dataclass 31class Edit: 32 op: str 33 target: str | list[str] 34 index: Any = None 35 args: dict = field(default_factory=dict) 36 where: Any = None 37 params: list[str] | None = None # restrict node targets to these roles / local names 38 label: str | None = None 39 40 @property 41 def replayable(self) -> bool: 42 if callable(self.where) or (self.index is not None and format_index(self.index) is None): 43 return False 44 return all(_jsonable_arg(v) for v in self.args.values()) 45 46 def to_dict(self) -> dict: 47 d: dict[str, Any] = {"op": self.op, "target": self.target} 48 if self.index is not None: 49 d["index"] = format_index(self.index) or "<unserializable>" 50 if self.args: 51 d["args"] = {k: _serialize_arg(v) for k, v in self.args.items()} 52 if self.where is not None: 53 d["where"] = self.where if isinstance(self.where, str) else "<callable>" 54 if self.params: 55 d["params"] = list(self.params) 56 if self.label: 57 d["label"] = self.label 58 if not self.replayable: 59 d["replayable"] = False 60 return d 61 62 @classmethod 63 def from_dict(cls, d: dict) -> "Edit": 64 if d.get("replayable") is False: 65 raise ValueError(f"edit {d.get('op')!r} on {d.get('target')!r} is not replayable") 66 args = dict(d.get("args", {})) 67 if d["op"] == "group": 68 args["edits"] = [cls.from_dict(e) for e in args.get("edits", [])] 69 return cls(op=d["op"], target=d["target"], index=d.get("index"), args=args, where=d.get("where"), 70 params=d.get("params"), label=d.get("label")) 71 72 def describe(self) -> str: 73 if self.label: 74 return self.label 75 tgt = self.target if isinstance(self.target, str) else ", ".join(self.target[:3]) + ( 76 "…" if len(self.target) > 3 else "") 77 idx = format_index(self.index) if self.index is not None else "" 78 a = ", ".join(f"{k}={_short(v)}" for k, v in self.args.items()) 79 w = f" where {self.where}" if isinstance(self.where, str) else "" 80 return f"{self.op}({a}) → {tgt}{idx or ''}{w}"
46 def to_dict(self) -> dict: 47 d: dict[str, Any] = {"op": self.op, "target": self.target} 48 if self.index is not None: 49 d["index"] = format_index(self.index) or "<unserializable>" 50 if self.args: 51 d["args"] = {k: _serialize_arg(v) for k, v in self.args.items()} 52 if self.where is not None: 53 d["where"] = self.where if isinstance(self.where, str) else "<callable>" 54 if self.params: 55 d["params"] = list(self.params) 56 if self.label: 57 d["label"] = self.label 58 if not self.replayable: 59 d["replayable"] = False 60 return d
62 @classmethod 63 def from_dict(cls, d: dict) -> "Edit": 64 if d.get("replayable") is False: 65 raise ValueError(f"edit {d.get('op')!r} on {d.get('target')!r} is not replayable") 66 args = dict(d.get("args", {})) 67 if d["op"] == "group": 68 args["edits"] = [cls.from_dict(e) for e in args.get("edits", [])] 69 return cls(op=d["op"], target=d["target"], index=d.get("index"), args=args, where=d.get("where"), 70 params=d.get("params"), label=d.get("label"))
72 def describe(self) -> str: 73 if self.label: 74 return self.label 75 tgt = self.target if isinstance(self.target, str) else ", ".join(self.target[:3]) + ( 76 "…" if len(self.target) > 3 else "") 77 idx = format_index(self.index) if self.index is not None else "" 78 a = ", ".join(f"{k}={_short(v)}" for k, v in self.args.items()) 79 w = f" where {self.where}" if isinstance(self.where, str) else "" 80 return f"{self.op}({a}) → {tgt}{idx or ''}{w}"
292def load_edits(path_or_json) -> list[Edit]: 293 if isinstance(path_or_json, str) and path_or_json.strip().startswith("["): 294 data = json.loads(path_or_json) 295 elif isinstance(path_or_json, (list, tuple)): 296 data = path_or_json 297 else: 298 with open(path_or_json, encoding="utf-8") as f: 299 data = json.load(f) 300 return [d if isinstance(d, Edit) else Edit.from_dict(d) for d in data]
31def register_op(name: str, default_roles: tuple[str, ...] | None = None): 32 """Decorator: ``@register_op("my_op")`` then ``net["fc1"].edit("my_op", k=3)``.""" 33 34 def deco(fn): 35 OPS[name] = OpDef(name, fn, default_roles, (fn.__doc__ or "").strip()) 36 return fn 37 38 return deco
Decorator: @register_op("my_op") then net["fc1"].edit("my_op", k=3).
186def equation_rule(kind): 187 """Register a custom LaTeX rule for a layer kind / class: see :mod:`deepvis.equations.rules`.""" 188 from .equations.rules import equation_rule as _er 189 190 return _er(kind)
Register a custom LaTeX rule for a layer kind / class: see deepvis.equations.rules.
193def scope(name: str): 194 """Name a region of a pure-JAX function so it shows up as one node (alias of ``jax.named_scope``).""" 195 import jax 196 197 return jax.named_scope(name)
Name a region of a pure-JAX function so it shows up as one node (alias of jax.named_scope).
25class Intervention: 26 name = "intervention" 27 28 def __call__(self, x, ctx: InterventionContext): # pragma: no cover 29 raise NotImplementedError 30 31 def _axis(self, ctx: InterventionContext) -> int: 32 ax = getattr(self, "axis", None) 33 return ctx.feature_axis if ax is None else ax 34 35 def __repr__(self) -> str: 36 fields = {k: v for k, v in self.__dict__.items() if not k.startswith("_")} 37 body = ", ".join(f"{k}={_short(v)}" for k, v in fields.items()) 38 return f"{self.name}({body})"
47class ablate(Intervention): 48 """Set neurons (features along the channel axis) to ``value`` — all of them if ``neurons`` is None.""" 49 50 name = "ablate" 51 52 def __init__(self, neurons=None, value: float = 0.0, axis: int | None = None): 53 self.neurons, self.value, self.axis = neurons, value, axis 54 55 def __call__(self, x, ctx): 56 if self.neurons is None: 57 return ctx.ops.zeros_like(x) + self.value 58 idx = ctx.ops.feature_index(x, self._axis(ctx), self.neurons) 59 return ctx.ops.set_index(x, idx, self.value)
Set neurons (features along the channel axis) to value — all of them if neurons is None.
62class mean_ablate(Intervention): 63 """Replace neurons by their mean over every other axis (batch/space) of the current input.""" 64 65 name = "mean_ablate" 66 67 def __init__(self, neurons=None, axis: int | None = None): 68 self.neurons, self.axis = neurons, axis 69 70 def __call__(self, x, ctx): 71 ax = self._axis(ctx) % len(x.shape) 72 other = tuple(i for i in range(len(x.shape)) if i != ax) 73 mean = x.mean(axis=other, keepdims=True) if ctx.ops.framework != "torch" else x.mean(dim=other, keepdim=True) 74 full = mean + ctx.ops.zeros_like(x) 75 if self.neurons is None: 76 return full 77 idx = ctx.ops.feature_index(x, ax, self.neurons) 78 return ctx.ops.set_index(x, idx, full[idx])
Replace neurons by their mean over every other axis (batch/space) of the current input.
81class amplify(Intervention): 82 """Multiply activations (optionally only some neurons) by ``factor``.""" 83 84 name = "amplify" 85 86 def __init__(self, factor: float, neurons=None, axis: int | None = None): 87 self.factor, self.neurons, self.axis = factor, neurons, axis 88 89 def __call__(self, x, ctx): 90 if self.neurons is None: 91 return x * self.factor 92 idx = ctx.ops.feature_index(x, self._axis(ctx), self.neurons) 93 return ctx.ops.set_index(x, idx, x[idx] * self.factor)
Multiply activations (optionally only some neurons) by factor.
96class clamp(Intervention): 97 """Clip activations into [min, max].""" 98 99 name = "clamp" 100 101 def __init__(self, min: float | None = None, max: float | None = None): # noqa: A002 102 self.min, self.max = min, max 103 104 def __call__(self, x, ctx): 105 return ctx.ops.clip(x, self.min, self.max)
Clip activations into [min, max].
108class steer(Intervention): 109 """Add ``alpha * vector`` along the feature axis (activation steering).""" 110 111 name = "steer" 112 113 def __init__(self, vector, alpha: float = 1.0, axis: int | None = None): 114 self.vector, self.alpha, self.axis = np.asarray(vector, dtype=np.float32), alpha, axis 115 116 def __call__(self, x, ctx): 117 v = ctx.ops.broadcast_feature(self.vector * self.alpha, x, self._axis(ctx)) 118 return x + v
Add alpha * vector along the feature axis (activation steering).
121class add_noise(Intervention): 122 """Gaussian noise on activations (fixed seed → reproducible).""" 123 124 name = "add_noise" 125 126 def __init__(self, std: float = 0.1, seed: int = 0): 127 self.std, self.seed = std, seed 128 129 def __call__(self, x, ctx): 130 n = np.random.default_rng(self.seed).normal(0, self.std, tuple(x.shape)).astype(np.float32) 131 return x + ctx.ops.asarray(n, x)
Gaussian noise on activations (fixed seed → reproducible).
134class replace(Intervention): 135 """Replace the activation by a constant/array, or by ``fn(x)``; optionally only some neurons.""" 136 137 name = "replace" 138 139 def __init__(self, value: Any, neurons=None, axis: int | None = None): 140 self.value, self.neurons, self.axis = value, neurons, axis 141 142 def __call__(self, x, ctx): 143 new = self.value(x) if callable(self.value) else self.value 144 if not callable(self.value): 145 from ..core.tensor import to_numpy 146 147 arr = to_numpy(new) # detaches torch tensors, copies jax arrays 148 new = ctx.ops.asarray(np.broadcast_to(arr, tuple(x.shape)) if self.neurons is None else arr, x) 149 if self.neurons is None: 150 return new 151 idx = ctx.ops.feature_index(x, self._axis(ctx), self.neurons) 152 src = new[idx] if tuple(new.shape) == tuple(x.shape) else new 153 return ctx.ops.set_index(x, idx, src)
Replace the activation by a constant/array, or by fn(x); optionally only some neurons.
156class custom(Intervention): 157 """Wrap any ``fn(x, ctx) -> x`` (or ``fn(x) -> x``).""" 158 159 name = "custom" 160 161 def __init__(self, fn: Callable): 162 self.fn = fn 163 try: 164 import inspect 165 166 self._nargs = len(inspect.signature(fn).parameters) 167 except (TypeError, ValueError): 168 self._nargs = 1 169 170 def __call__(self, x, ctx): 171 return self.fn(x, ctx) if self._nargs >= 2 else self.fn(x)
Wrap any fn(x, ctx) -> x (or fn(x) -> x).
174def intervention(fn: Callable) -> custom: 175 """Decorator turning a function into an intervention.""" 176 return custom(fn)
Decorator turning a function into an intervention.
225def patch(net: "Net", source, target, at, neurons=None) -> PatchResult: 226 """Activation patching: run ``target`` but splice in ``at``'s activations from ``source``. 227 228 ``source`` / ``target`` are inputs (a tensor/array or a tuple of positional args). 229 """ 230 src_args = source if isinstance(source, tuple) else (source,) 231 tgt_args = target if isinstance(target, tuple) else (target,) 232 ids = net._resolve_nodes(at) 233 clean = net.backend.run(src_args, {}, record=ids) 234 corrupted = net.backend.run(tgt_args, {}, record=None).output 235 fns = {nid: [replace(clean.acts[nid], neurons=neurons)] for nid in ids} 236 patched = net.backend.run(tgt_args, {}, record=None, interventions=fns).output 237 return PatchResult(clean.output, corrupted, patched, at)
Activation patching: run target but splice in at's activations from source.
source / target are inputs (a tensor/array or a tuple of positional args).