Skip to content

Changelog

0.13.0 (2026-11-21)

  • Enforce registered-state and mid-forward mutation checks on PreparedNetwork generated execution with thread-safe signature updates, while reducing wrapper and generated-forward overhead so batch-1 CPU MLP execution beats nn.Sequential.
  • Unify InferenceCache and streaming session guards into a single low-overhead traversal, reuse active device/stream/autocast context across layers, and add mul, mish, softplus, and clamp to the streaming tokenwise contract.
  • Accelerate GatedDeltaAttention (decay_kind="channel") via midpoint-shifted factored batched matmuls with overflow fallback and a direct t=1 recurrent decode fast path; preserve conv_q/conv_k/conv_v hooks and handle T=0 inputs safely.
  • Vectorize Mamba2 chunked SSD evaluation, eliminate its redundant zxbcdt copy, add a direct t=1 recurrent decode fast path, and upcast dt/A_log before softplus/exp to prevent float16 overflow.
  • Fix LatentAttention.absorb_weights() to avoid autograd graph leaks, inference_mode cache crashes, and stale weights after load_state_dict(); add unabsorb_weights(); replace absorbed einsum calls with matmul/F.linear; enable FlashAttention on cached prefill; and pack k_up/v_up projections.
  • Eliminate per-token FlexAttention block-mask recompilation during single-token cached Attention decode, bound _mask_cache memory by storing a single largest window mask per configuration, avoid caching inference tensors in _get_causal_bias(), and preserve autocast query/key dtypes in Attention and LatentAttention.
  • Fix MoE torch.autocast dtype mismatches across grouped, padded, sparse, and fallback dispatch modes; eliminate redundant token gathers; single-pack padded execution; replace tile=1 sparse fallback collapse with per-expert sliced F.linear; and pack JointAttention QKV projections.
  • Optimize EqualLinear (scale smaller operand), RMSNorm(zero_centered=True) (fused F.rms_norm), GRN (fused addcmul), Hopfield and SpatialAttention (gated SDPA), RoPE (pre-duplication trig), SinusoidalEmbed (cached fp32/fp64 frequencies), and DeploymentModel/export (pre-parsed input guards and single-pass direct-storage SHA-256 hashing).
  • Guard packed projection storage against .weight.data reassignments without rebind_state(), and extend init_policy="depth_scaled" to composite transformer_block/resblock modules and all moe experts.
  • Fix shape/argument validation and numerical edge cases in transformer_block (head_dim, empty cached node_id), 2D axial RoPE (head_dim % 4 == 0, H * W == T, NTK exponent, compiled start slice), dy_tanh/drop_path/snake (rank-polymorphic resolution, bfloat16 drop sampling, float16 NaN and channel inference), deconv1d(causal=True), resblock bottleneck group_norm, and matmul.
  • Fix static profiler parameter and FLOP formulas across resblock, cross_attention, joint_attention, dy_tanh, snake, swiglu, feed_forward, transformer_block, deconv/deconv1d, mamba2, latent_attention, gated_delta_attention, patch_embed, adaln_zero, hopfield, and spatial_attention; complete plan.diff() for rewired inputs, initialization, trainability, and multi-output shape deltas; fix pass-through edges in plan.to_mermaid(); and remove O(N²) tie scans and redundant serialization in resolver.py and types.py.

0.12.0 (2026-11-20)

  • Preserve hooks and custom expert projections across MoE dispatch modes and compute group boundaries from sorted routes to reduce runtime and temporary allocations.
  • Reuse length-independent rotary tables during decoding, preserve YaRN length and inference-to-training semantics, bound local-attention KV storage by its window, and reduce per-token state-guard traversal.
  • Isolate FlexAttention compilation across execution modes and head layouts, and retain its softcap storage across CUDA graph replay. On PyTorch 2.6, automatic attention uses the reference implementation for gradient-carrying calls and explicit Flex training reports the upstream gradient issue. Native deployment fingerprints support attention code that indexes tensors with slices and ellipses.
  • Load standalone native packages from read-only directories with checksum and environment verification. Managed caches still coordinate readers and writers.
  • Move local branch and worktree housekeeping to an explicit maintainer check and recognize an optional packaging tool correctly in checkouts with a local build/ directory.
  • Enforce shape, dtype, device and batch contracts under compiled prepared execution, including intermediate custom operator outputs and cold full-graph calls on PyTorch 2.6.
  • Honor non-reentrant activation checkpointing for first-layer trainable weights with ordinary input tensors, and reduce dispatch overhead in eager and prepared execution.
  • Accept named tensor inputs called cache alongside the positional-input convention for incremental sessions.
  • Include parameter ties in plan digests and diffs, count shared storage once in build receipts and resource limits, and migrate saved tied plans after verifying their original checksums. parameter_counts(plan, unique=True) attributes shared weights to their first owner for model totals.
  • Report activation bytes by port dtype, respect non-affine normalization, and expose decoder cache capacity and latent-attention absorption when estimating persistent storage.
  • Export all bundled recipes as standalone PyTorch models with their helper functions, initialization, trainability and nested parameter ties. Unsupported custom dependencies now identify the affected node during export.
  • Load operator contracts on demand for CLI inspection, diagrams and recipe checks. Static inspection now warns about the deprecated --device option and rejects unrecognized device names.
  • Add a correctness and optimization review with execution parity findings, CPU latency measurements, and CUDA memory comparisons.
  • The CPU ParticleGAN example and integration tests use ParticleGAN 0.11.0 with the explicit BiSPF recipe.
  • Preserve the tested source tag when publishing a GitHub release draft.
  • Releases from master mirror the same tested wheel and source archive to GitHub after PyPI verifies their hashes.
  • Publish an unpublished package version to PyPI after it merges to master and passes the distribution checks.

0.11.0 (2026-11-04)

  • Add opt-in performance measurements and a hardware-specific report covering prepared setup/inference/training, bounded replay memory, incremental decoding, packed operators, fused attention and native deployment startup/runtime.
  • Add exclusive native deployment execution on supporting PyTorch loaders, with host-call and CUDA-stream guards, and reject root hooks or custom root forwards that cannot preserve export semantics.
  • Use packed QKV projections in prepared self-attention and gated delta attention, and dispatch prepared softcap/sliding-window self-attention to fused FlexAttention without dense window masks, including incremental position offsets.
  • Add prepared graph execution sharing existing parameters, optimizer references and checkpoint names, with generated tensor lifetimes, optional bounded CUDA graph replay, independent or borrowed outputs, and measured inference strategy selection.
  • Keep CUDA replay buffers alive until pending cross-stream work finishes when a prepared executor is garbage-collected, preventing allocator reuse from corrupting unrelated tensors.
  • Validate incremental graphs against tokenwise sequence contracts, unify the public inference cache APIs, and generate cached forward programs after the first checked input signature instead of rechecking every layer on every decoding step.
  • Rebuild checked shape programs after rebind_state() so the first call after a layer replacement uses the new layer.
  • Add opt-in packed QKV, cross-attention KV, SwiGLU and expert parameter storage while preserving parameter objects, optimizer references, gradients and checkpoint keys; add bounded selected-route MoE execution with adaptive grouped/padded dispatch and an explicit memory threshold.
  • Add an optional FlexAttention backend for softcap and sliding-window attention with bounded block-mask caching and explicit fallback for unsupported devices, dtypes, dense bias and attention dropout.
  • Add native inference deployment through hndl.deployment.export and load, with reusable AOTInductor packages, weight/operator/environment fingerprints, exact runtime input guards, checksum verification, atomic package replacement, and bounded artifact storage.
  • Add bounded incremental inference caches for causal attention, transformer blocks, latent attention (including compressed weight absorption), Mamba2, gated delta attention, learned positions and RoPE, with absolute position offsets, reusable KV storage, recurrent/convolution state, and session validation.
  • Guard cached decoding against computational buffer changes, including frozen weight buffers, and reject model state without mutation version counters; reject overlapping graph sessions and active resets, and bind each CUDA session to one stream until reset.
  • Dispatch pretrained shape callbacks with named layer selections correctly, preserving legacy positional output callbacks without binding layers twice.
  • Keep ParticleGAN as a separately installed dependency of its optional CPU example and integration tests; document frozen-base low-rank training and routed particle-slider integration while HNDL requires only PyTorch.
  • Label standalone generated Python source with the current HNDL package version.

0.10.0 (2026-10-23)

  • Require patched build tooling (setuptools 84.2.1 and wheel 0.46.2 or newer) to prevent wheel unpack permission changes outside the extraction directory.
  • Milestone 5 Gate Iteration 1 Remediation:
  • registry.py: Removed top-level PyTorch import (from torch import nn), deferring nn import to Registry.subgraph, ensuring that importing hndl does not eagerly load PyTorch into sys.modules in clean Python processes.
  • PEP 562 Lazy Loading Tests: Added isolated subprocess verification tests to tests/test_m5_tooling_lifecycle.py and tests/e2e/test_v010_e2e.py certifying that import hndl does not introduce torch into sys.modules.
  • resolver.py Pattern Provenance Tracking: Enhanced _Solver.patterns() to record provenance origin labels across pattern variables and surface detailed "established by ... and required by ..." origin labels upon shared dimension contradictions.

  • Milestone 5: DX, IDE Autocomplete & Type Stubs:

  • OperatorNamespace.__dir__: Added dynamic alias listing enabling tab completion across all 84 registered operators.
  • Operator Factory Docstrings & Signatures: Attached docstrings and inspect.Signature to dynamic operator factories synthesized in hndl.ops.
  • Type Stub Generator (src/hndl/capture.pyi): Generated and verified comprehensive .pyi interface stub for hndl.ops covering all 84 built-in operators with typed signatures and overloads, verified via python -m hndl.docs --check.
  • PEP 562 Lazy Loading: Added module __getattr__ in hndl.__init__ for lazy loading of hndl.torch without eager torch imports.
  • Manifest Exports: Exported Symbol and NodeView in hndl.__all__.

  • Milestone 5: Static Profiling, Visualization, CLI & Training Lifecycle:

  • Static Zero-Compute Profiler (plan.profile()): Pure Python analytical profiler computing total and active parameter counts across all 84 operators (including routing-aware active count for sparse MoE), analytical forward/training FLOPs (1 MAC = 2 FLOPs), slot-recycled peak activation memory bytes, and KV/recurrent state memory bytes (attention, MLA, KDA, Mamba2) with zero PyTorch allocation.
  • Mermaid Flowchart Export (plan.to_mermaid()): Renders ResolvedPlan as clean, shape-annotated Mermaid diagram with styled input/output subgraphs and edge connectivity.
  • Plan Diffing (plan.diff(other)): Structural and semantic comparison between two resolved plans reporting added, removed, and modified nodes, shape deltas, parameter delta, and FLOP delta.
  • CLI Tooling (hndl executable): Implemented command-line entrypoint with inspect (with --sidecar, --batch-size, --profile), mermaid (with --out), and check subcommands for validating individual recipe files or directories.
  • Optimizer Parameter Groups (model.param_groups(weight_decay=0.01)): Deterministic partitioning of model parameters into weight decay groups (2D+ weights) and no-decay groups (1D biases, norms, embeddings, scalars).
  • Selective Activation Checkpointing (build(..., checkpoint=...)): Gradient checkpointing support for heavy blocks or user-selected node IDs in training mode.
  • Graph-Aware Depth-Scaled Initialization (build(..., init_policy="depth_scaled")): Topological graph traversal identifying residual branch exit projections and scaling initialization weights by $1/\sqrt{2N_{\text{layers}}}$.
  • Stateful Autoregressive InferenceCache: Cache container supporting autoregressive decoding for attention, MLA, KDA, and Mamba2 with dictionary interface, per-node or full reset, and output attribute forwarding.

  • Milestone 5: Diagnostics & Provenance Chains:

  • Fuzzy Error Suggestions: Added difflib.get_close_matches suggestions across operator aliases in parser and registry, arguments and policies in normalize_arguments, undefined variables in config.py, parameter targets in _prepare_parameter_settings, and node keys in GraphModule.__getitem__.
  • Operator Prefix Diagnostic: Added explicit .hndl syntax diagnostic directing users to call operators directly without ops. prefix.
  • Solver Shape Provenance: Implemented origin tracking in _Solver, reporting establishing origin labels and full conflicting shapes in E_CONSTRAINT and E_RESHAPE.
  • Loop Naming Separation: Separated digit-ending node names from loop iteration indices using an underscore (pwconv1_0).
  • Caller Line Number Capture: Recorded caller line numbers (sys._getframe(1).f_lineno) during native Python capture.

  • Milestone 4 Gate Iteration 1 Remediation:

  • codegen.py: Corrected parameter dictionary lookups in _format_module_constructor for embedding (dim), layer_norm (D, affine, bias), and rms_norm (D, affine), enabling zero-dependency standalone instantiation and execution.
  • codegen.py Subgraphs & Custom Modules: Applied textwrap.dedent to extracted custom module class sources; cleanly embedded composite subgraphs (Registry.subgraph) as standalone Submodel_<alias> PyTorch classes with zero dependencies on closures and zero indentation errors.
  • _parser.py: Fixed unpacked assignment constant rebinding diagnostic to report the exact offending constant rather than non_discard[0].
  • _parser.py & config.py: Enforced E_BINDING rejection when macro parameters collide with defined constants, and ensured macro formal parameters take precedence over constants during parsing and evaluation.

  • Milestone 4: Extensibility & Ecosystem Interoperability:

  • .hndl Constants: Added top-level immutable scalar constant declarations (D = 64) with re-binding guard (E_BINDING), AST constant folding and substitution in operator calls, kwargs, and loops.
  • .hndl Def Macros: Added non-recursive AST-expanded macro definitions (def name(params): ... return out) with parameter substitution, statement budgets, and automatic unique scoped node prefixes.
  • .hndl Tuple Loops: Added unrolled literal tuple loops (for c in (32, 64): ...) enabling clean channel progression and block repetition.
  • Python Scoping (ops.scope): Context manager for prefixing node names during callable capture, supporting nested scopes and disambiguating multi-stage networks.
  • Composite Subgraphs (registry.subgraph): Added Registry.subgraph(alias, plan) to package and register a resolved plan as a first-class composite operator module with clean tensor I/O and autograd backpropagation.
  • Declarative Weight Tying: Added tie={"weight": "source_node.weight"} in capture and resolver, with topological dependency enforcement, cycle detection, shape/dtype validation, storage pointer sharing (data_ptr()), and gradient aggregation.
  • Post-Build State Mutation: Added model.allow_state_mutation() context manager and model.rebind_state() method on GraphModule to bless parameter updates and submodule grafting during PEFT, LoRA adapter injection, and quantization.
  • Zero-Dependency PyTorch Codegen: Added plan.to_python_source(class_name="Model") emitting self-contained, human-readable standalone PyTorch source code with line-by-line shape annotations, zero HNDL runtime imports, and numerical round-trip parity.
  • Checkpoint Loader (hndl.torch.load_weights): Checkpoint state dict loader supporting .pt, .safetensors, and in-memory dicts with key remapping and automatic state rebinding.
  • Plugin Discovery (registry.discover_plugins): Entry-point loader discovering third-party HNDL operators registered under the hndl.operators entry-point group.

  • Milestone 3 Gate Iteration 1 Remediation:

  • joint_attention: Added qk_norm="l2_norm" per-head L2 normalization in both module forward execution and independent reference oracle.
  • mamba2: Added chunk_size argument, implemented semi-separable chunked recurrence in forward() with safe intra-chunk masked decay and inter-chunk state propagation, added joint depthwise convolution over $[x_{ssm}, B, C]$, cleaned up dead d_has_bias argument, and retained independent sequential recurrence in _reference(module) ($< 1\times 10^{-4}$ numerical parity).
  • Operator Identities: Registered canonical identities (ssd@1, mmdit_attention@1, dynamic_tanh@1, stochastic_depth@1, where@1, snake@1) across all new v0.10 built-in operators.
  • snake: Added shape constraint validation in _relation ensuring mismatched channel dimensions raise E_CONSTRAINT during graph resolution.
  • rope: Updated shape contract to x[B, ...] -> out[B, ...] supporting rank-4 [B, H, T, D_h] tensor resolution and execution with autograd gradients and reference parity.
  • Recipes & Docs: Cleaned up drafting notes in clip_dual_encoder_tiny.json and synchronized operator documentation.

  • 6 New Built-In Operators (expanding catalog from 78 to 84):

  • mamba2 (ssd@1, sequence category): State Space Duality block featuring causal 1D convolution, semi-separable chunked recurrence, gated RMSNorm, discretized continuous-time state-space parameterization, full autograd gradient propagation, and PyTorch reference oracle.
  • joint_attention (mmdit_attention@1, sequence category): Dual-stream multimodal attention with modality-specific QKV projections, joint SDPA over concatenated sequence contexts, token unpooling/split, and per-modality output projections supporting RMSNorm and L2 QK-normalization.
  • dy_tanh (dynamic_tanh@1, activation category): Dynamic Tanh activation and normalization with learned scalar frequency alpha and per-channel affine gamma / beta scaling.
  • drop_path (stochastic_depth@1, regularization category): Residual stochastic depth dropping sample paths across batches with inverse survival probability keep-scaling in training mode and exact identity in evaluation mode.
  • where (where@1, core category): Ternary element-wise selection out = torch.where(cond, a, b) with boolean condition enforcement (E_DTYPE) and bidirectional multi-port shape inference.
  • snake (snake@1, activation category): Learned periodic activation $x + \frac{1}{\alpha + \epsilon} \sin^2(\alpha x)$ with channel-wise frequency parameter learning across channels-first and channels-last layouts.
  • SOTA Operator Extensions (Arg(..., since="0.10.0")):
  • rope: Extended with frequency scaling options (rope_scaling in "none", "linear", "ntk", "yarn", "llama3"), scale factor rope_scale, 2D axial RoPE via spatial_shape=(H, W), and rank-4 [B, H, T, D_h] tensor support.
  • attention & latent_attention: Forwarded rope_scaling, rope_scale, and spatial_shape to internal RoPE and decoupled RoPE layers.
  • resblock: Added kind="bottleneck" (3-convolution residual bottleneck with expansion ratio) and configurable activation ("relu", "silu", "gelu").
  • transformer_block: Added decoupled head_dim, window_size sliding-window local context masking, logit_softcap, qkv_bias, out_bias, zero_centered RMSNorm, and post_norm Post-LN architecture layout.
  • deconv1d: Added causal=True zero-lookahead left-padded transposed 1D convolutions and channels_last=True [B, T, C] layout support.
  • adaln_zero: Added gate=False support emitting a single out port with 2D (shift, scale) modulation without redundant residual gating parameters.
  • moe: Added routed_scaling_factor parameter scaling routed expert outputs for DeepSeek-V2/V3 alignment.
  • conv & conv1d: Added policy="same3" and groups="depthwise" automatically tying input/output channels to group count.
  • Constraint Solver Rank-5 & reshape(-1, ...) Negative Dimension Support:
  • Extended solver SUPPORTED_RANKS = (2, 3, 4, 5) across operator.py, resolver.py, reshape.py, and permute.py, enabling native 5D video tensor [B, C, T, H, W] contract resolution and permutation.
  • Added single negative dimension -1 support in reshape(shape) at any non-batch position, inferring unknown dimension via s.product("x", "out").
  • 4 New Authored Network Recipes (expanding recipe catalog from 21 to 25):
  • Added convnext_v2_tiny (.hndl and .json, 77,900 parameters) exercising Global Response Normalization (GRN), DropPath stochastic depth, depthwise convolution, and learned residual scaling.
  • Added encodec_autoencoder_tiny (.hndl and .json, 83,009 parameters) exercising causal 1D strided convolution, periodic Snake activation, and causal 1D transposed convolution.
  • Added clip_dual_encoder_tiny (.hndl and .json, 89,920 parameters) exercising QuickGELU, cls_token, gather_token, L2 normalization, matrix multiplication, and scale.
  • Added nerf_coord_field (.hndl and .json, 8,075 parameters) exercising random Fourier features, log-spaced sinusoidal embeddings, rotary embeddings, tensor splitting, and dynamic tanh activation.
  • Catalog and Documentation Synchronization:
  • Synchronized built-in operator count from 78 to 84 across SPEC.md, IMPLEMENTATION.md, README.md, and tests/test_package.py.
  • Scaled network example test suite tests/test_network_examples.py across all 25 recipes.

  • gated_delta_attention non-reciprocal intra-chunk decay formulation: Replaced reciprocal intra-chunk decay factorization ($\exp(\text{cum}_i) \cdot \exp(-\text{cum}j)$ with clamping) with non-reciprocal forward causal relative decay $\Delta} = (\text{cum}_i - \text{cumj).\text{clamp}(\text{max}=0.0)$, ensuring exact mathematical reference parity ($< 1\times 10^{-4}$) for large chunk sizes ($C \ge 128$) and strong decay rates ($A$ for channel decay), eliminating reciprocal overflow to $+\infty$, and guaranteeing 100% finite backward gradients across extreme decay regimes.}} \ge 2.0$), maintaining strictly bounded peak activation memory ($46.26 \text{ MB

  • moe 16-byte stride alignment & float16 compilation stability: Enforced 16-byte row stride alignment checks across both CPU and CUDA in MixtureOfExperts, routing unaligned byte layouts cleanly to batched bmm fallback; under torch.compile, restricted torch._grouped_mm dispatch to bfloat16 and routed float16 to bmm to prevent Dynamo FakeTensor meta registration errors on CUDA < 13.3 or pre-Hopper/SM < 90 devices while maintaining 0 graph breaks.
  • gated_delta_attention empty batch ($b=0$) & backward numerical stability: Replaced ambiguous -1 dimension with deterministic log_alpha.shape[-1] in chunk reshaping to support empty-batch inputs ($b=0$) with full autograd graph preservation; lowered single-precision max_neg_exp clamping threshold from $85.0$ to $45.0$ across full and tail chunk paths, completely eliminating float32 dot-product overflow into +inf during backward backpropagation and preventing NaN parameter gradients under strong decay rates.
  • latent_attention linear bias rejection in absorb_weights: Guarded LatentAttention.absorb_weights() to raise HNDLError("E_UNSUPPORTED", ...) when projections contain linear biases, ensuring weight absorption is strictly applied to unbiased configurations without silent numerical drift.
  • test_peak_memory.py warmup pass for steady-state slot recycling: Added an explicit warmup forward pass before clearing cache and resetting peak memory stats in test_graph_module_dead_slot_clearing(), verifying steady-state slot recycling on GraphModule's compiled fast path.

  • moe grouped GEMM & zero-sync sparse dispatch: Replaced eager Python expert loops and host-device synchronizations with token sorting via torch.argsort and zero-sync grouped execution via torch._grouped_mm (and batched bmm fallback with zero Dynamo graph breaks under torch.compile(..., fullgraph=True)), scaling with sparse $O(k)$ compute across expert counts.

  • gated_delta_attention 4D tensor core vectorization: Eliminated 5D tensor materializations in _chunk_forward via factorized 4D Tensor Core operations, vectorized intra-chunk triangular solve ($E_{\text{intra}}$ and $K_{\text{solve}}$) across all chunks outside the recurrence loop, fused causal depthwise Q/K/V convolutions into a single grouped 1D convolution, and clamped negative exponents to ensure complete numerical stability under extreme decay rates.
  • attention, cross_attention & latent_attention runtime optimizations: Added sliding-window and causal mask caching in Attention and CrossAttention (with automatic cache invalidation on _apply()), eliminated tensor duplication on GQA soft-cap fallback paths via zero-copy broadcast views, eliminated redundant torch.cat allocations in LatentAttention, and added inference weight absorption (absorb_weights()) compressing KV representations by $5.7\times$.
  • GraphModule dead activation slot recycling & build() fast path: Implemented immediate intermediate activation slot clearing (values[slot] = None) upon final consumer completion in GraphModule._execute to reclaim VRAM during deep network forward passes, optimized steady-state store checking via fast short-circuit comparison generators, and used torch.set_default_dtype(dtype) during unseeded module construction to eliminate duplicate float32 allocations on GPU.
  • Expanded performance & memory benchmark suite: Added tests/benchmark/test_training_latency.py benchmarking forward + backward execution latency across all 21 example networks, tests/benchmark/test_peak_memory.py tracking peak activation memory and slot clearing efficiency, and tests/benchmark/test_sota_operators_latency.py benchmarking sparse MoE scaling, GDA 4D chunkwise forward latency, MLA weight absorption, and GQA sliding-window attention.
  • Milestone 1 forensic bug remediation: Corrected produced_is_compute port tracking in GraphModule so floating-point module casts (.double(), .half(), .to()) track compute outputs accurately; reverted SinusoidalEmbed._apply buffer override to align module state bytes with build receipt while maintaining float32 precision during forward evaluation; and synchronized deepseek_moe_tiny parameter count assertion to 1,181,312.
  • cast runtime crash & buffer pollution remediation (B-01): Eliminated _prototype buffer pollution from module state_dict() and buffers() in Cast, added "float64" to DTYPES, and updated GraphModule._effective_dtype to track compute-domain ports and leave explicit integer, boolean, and float64 ports unchanged under .half() or .to().
  • torch.compile RoPE cache poisoning and device retention (B-02): Added cache clearing in _apply() across RoPE, Attention, and LatentAttention modules to eliminate device retention on .to(device) or .cpu(), bypassed caching when torch.compiler.is_compiling() is true, and added max-length cache slicing for variable-length sequence evaluation.
  • gated_delta_attention float16 backward autograd stability (B-03): Evaluated log-space gating decay log_alpha and recurrence accumulation in calc_dtype (float32/float64), preventing reciprocal/exponential overflow and subsequent NaN gradients during reduced-precision backward passes.
  • grn and sinusoidal_embed float16 numerical precision (B-04): Evaluated spatial channel L2 norm in float32 within GRN to prevent overflow on large spatial dimensions, and evaluated frequency angles in float32 while preserving freqs buffer precision across .half() in SinusoidalEmbed.
  • matmul._relation rank inference monotonicity (B-05): Deferred rank guesses past Sweep 0 to maintain monotonic constraint narrowing and support backward rank inference from output contracts, and updated Matmul docstring to document rank 2, rank 3, and rank 4 batched matrix products.
  • conv1d(causal=True, stride > 1) shape interval inference (B-06): Emitted exact pre-image length intervals s.interval("x", length_axis, (out_len - 1) * stride + 1, out_len * stride) instead of raising E_AMBIGUOUS during backward length resolution.
  • pretrained native registry contract & shape_fn support (B-07): Native contract and shape_fn support implemented directly in Registry.pretrained_provider, eliminating monkey-patching in pretrained.py, inspecting signatures cleanly without trial-and-error exception swallowing, and guarding output port validation when contract="ids".
  • adaln_zero gate=False support and recipe alignments (B-08): Added gate parameter to adaln_zero supporting scale/shift modulation without residual gating, updated dit_tiny.hndl and deepseek_moe_tiny.hndl recipes with verified parameter counts and semantic sidecar digests.
  • Multi-output unpacking multiple _ discard targets (B-09): Permitted repeated wildcard target _ in unpacking assignments without raising false E_ASSIGN duplicate target errors, and omitted _ from unrolled loop local variable bindings.
  • l2_norm dim validation, transformer_block eps propagation & extra_repr (B-10): Validated dim bounds in l2_norm._relation, forwarded eps=eps to Attention in transformer_block, and added informative extra_repr() implementations to all v0.9.0 operators.

0.9.0 (2026-10-17)

  • MoE float16 backward autograd stability: Clamped router score summation denominator to 1e-4 in moe sigmoid scoring, preventing reciprocal overflow to +inf and subsequent NaN gradients during float16 backward backpropagation.
  • Numerical stability in MoE and Gated Delta Attention: Fixed float16 underflow in moe sigmoid scoring router and gated_delta_attention cumulative decay, preventing NaN outputs during reduced-precision evaluation.
  • Authored SOTA network recipes: Added 8 frontier neural network recipes with complete .hndl declarations and .json sidecars in examples/networks/:
  • llama_tiny: 64-token LLaMA-style causal language model with pre-RMSNorm, 4-head RoPE causal attention, and bias-free SwiGLU feed-forward networks (918,656 parameters, 27 nodes).
  • deepseek_moe_tiny: Hybrid shared and routed mixture-of-experts causal decoder pairing pre-RMSNorm and RoPE attention with parallel shared SwiGLU and top-2-of-4 routed experts (922,240 parameters, 19 nodes).
  • whisper_seq2seq_tiny: Audio speech recognition seq2seq architecture with 2-layer 1D convolutional acoustic stem, bidirectional transformer encoder, and causal decoder with cross-attention over heterogeneous float32 spectrogram and int64 token inputs (159,296 parameters, 20 nodes).
  • convnext_tiny: ConvNeXt vision classifier with 4×4 patchifying stem convolution, 7×7 depthwise convolutions with GroupNorm, inverted 1×1 pointwise bottlenecks (4× expansion), and learned residual scale (76,876 parameters, 19 nodes).
  • espcn_super_res: Efficient Sub-Pixel Convolutional Neural Network for 2× image super-resolution exercising backward channel inference through pixel_shuffle(2) and output contract (26,796 parameters, 6 nodes).
  • kimi_linear_tiny: 3:1 hybrid causal decoder interleaving 3 Kimi Delta Attention (KDA) layers with fine-grained channel-wise decay and 1 NoPE Multi-Head Latent Attention (MLA) layer (955,808 parameters).
  • qwen3_gqa_qknorm: Qwen3-style causal decoder pairing pre-RMSNorm, 4:2 Grouped-Query Attention, per-head QK-RMSNorm, high-frequency RoPE ($\theta=10^6$), and bias-free SwiGLU (853,376 parameters).
  • dit_tiny: Diffusion Transformer at 32×32 image scale with 4×4 patch embedding stem, AdaLN-Zero conditioning modulation, QK-normalized self-attention, SwiGLU feed-forwards, and sub-pixel unpatchify head (695,472 parameters).
  • Network recipe test suite scaling: Scaled tests/test_network_examples.py across all 21 authored network recipes (64 test cases covering sidecar metadata completeness, round-trip JSON semantic digest invariance, and CPU/CUDA module construction and finite autograd backward gradient checks).
  • Global operator catalog count synchronization: Updated operator count from 69 to 78 across 12 categories in SPEC.md, IMPLEMENTATION.md, README.md, tests/test_package.py, and tests/e2e/test_audit_remediation_e2e.py.
  • conv1d causal & sequence extensions: Added causal=True left-padding with a bijective $L_{out} == L_{in}$ constraint solver relation when stride=1, and added channels_last=True for direct [B, T, C] sequence evaluation.
  • rms_norm zero-centered scaling: Added zero_centered=True initializing weights to 0.0 and evaluating as $(1 + \text{weight}) \cdot \text{RMSNorm}(x)$ for Gemma-style models.
  • layer_norm bias-free option: Added bias=False to LayerNorm for constructing bias-free LayerNorm blocks.
  • adaptive_norm rank-3 sequence support: Extended adaptive_norm to accept rank-3 sequence tensors [B, T, C] alongside rank-4 image tensors [B, C, H, W].
  • matmul multi-rank batching: Generalized matmul to arbitrary leading batch dimensions (a[B, ..., N, K], b[B, ..., K, M] -> out[B, ..., N, M]), supporting both rank-3 and rank-4 multi-head batched matrix multiplication.
  • moe 3-projection SwiGLU experts, sigmoid scoring & bias toggle: Added expert_kind="swiglu" supporting 3-projection SiLU-gated feed-forward experts, scoring="sigmoid" for top-k normalized sigmoid router affinity, and bias=False for unbiased expert linear projections.
  • attention GQA, QK-Norm, sliding-window & logit soft-capping: Extended attention with kv_heads for fused Grouped-Query / Multi-Query Attention (enable_gqa=True), decoupled head_dim override, per-head qk_norm ("rms_norm" and "l2_norm"), window_size for sliding-window local context masking, logit_softcap with explicit tanh scaling fallback, and configurable rope_theta.
  • cross_attention GQA, decoupled head_dim, narrow biases & QK-Norm: Extended cross_attention with kv_heads for GQA, decoupled head_dim, narrow projection bias controls (qkv_bias, out_bias), per-head qk_norm, and logit_softcap.
  • transformer_block SwiGLU, explicit hidden width, RoPE & bias propagation: Extended transformer_block with ffn_kind="swiglu" for 3-projection gated feed-forwards, explicit inner FFN width hidden, forwarded rope, rope_theta, kv_heads, and qk_norm to attention, and block-wide bias=False propagation.

  • Pretrained provider contract hardening: Registered architecture providers on registry.pretrained_provider can specify an optional shape_fn callback to compute output shapes directly without executing on PyTorch's meta device (preventing crashes on custom Triton and CUDA kernels lacking fake-tensor registrations), and can declare contract="ids" to consume rank-2 [B, T] int64 token IDs without triggering E_DTYPE.

  • cast operator & edge dtype propagation: Added cast@1 (core category) supporting explicit dtype conversions across graph edges (float32, float16, bfloat16, float64, int64, int32, bool, and 'compute'), with resolver edge propagation updated to track cast output dtypes.
  • l2_norm operator: Added l2_norm@1 (normalization category) providing parameter-free L2 normalization with configurable dim and numerical eps.
  • grn operator: Added grn@1 (normalization category) implementing ConvNeXt-V2 Global Response Normalization with spatial L2 channel pooling and zero-initialized recalibration parameters.
  • sinusoidal_embed operator: Added sinusoidal_embed@1 (sequence category) providing deterministic log-spaced sinusoidal timestep and coordinate embeddings.
  • deconv1d operator: Added conv_transpose1d@1 (alias deconv1d, convolution category) with up2 policy and bidirectional conv_transpose_axis length resolution.
  • adaln_zero operator: Added adaln_zero@1 (normalization category) providing rank-3 adaptive LayerNorm-Zero conditioning modulation for Diffusion Transformers with zero-initialized linear projections.
  • rope operator: Added rope@1 (sequence category) providing standalone rotary position embeddings for sequence tensors with configurable heads and base frequency theta.
  • latent_attention operator: Added latent_attention@1 (sequence category) implementing DeepSeek and Kimi Multi-Head Latent Attention (MLA) with low-rank KV compression, decoupled RoPE, and position-free NoPE mode.
  • gated_delta_attention operator: Added gated_delta_attention@1 (sequence category) implementing Kimi Delta Attention (decay_kind="channel") and Gated DeltaNet (decay_kind="head") with chunkwise parallel WY/DPLR Tensor Core evaluation, causal depthwise convolution, per-head L2 normalization, and step-by-step sequential recurrence reference oracle.

0.8.2 (2026-10-15)

  • C-speed steady-state module verification: GraphModule._execute implements a 2-tier store verification fast path caching module and parameter IDs, validating steady-state forward passes in C without per-call tuple or torch.device allocations (<1 µs on mlp, <10 µs on resnet18).
  • Zero-allocation forward dispatch: Standard forward invocations with positional arguments bind directly to input tuples, single-input nodes return C 5-tuple signatures without list comprehensions, multi-input nodes use pre-instantiated operator.itemgetter, and single-output networks return scalar output tensors without allocating intermediate output dictionaries.
  • Liveness-based activation slot recycling: _build_fast_program analyzes tensor liveness intervals with min-heap free-list recycling, reusing dead intermediate activation slots to lower peak inference memory by up to 84% on standard networks (resnet18, unet_small, vit_tiny).
  • Non-mutating torch.compile tracing: GraphModule._resolve_shapes avoids mutating self._compiled during TorchDynamo tracing, ensuring compile transparency and dynamic shape evaluation without cache interference.
  • Construction & registration hook speedups: _registration_hook bypasses KeyError exceptions using direct dictionary lookups on watched storage, construct() calls constructors directly on CPU without torch.device("cpu") overhead when torch_function_stack is empty, and _build() hoists with registry.activated(): outside node loops.
  • Pretrained caching & loader consolidation: @lru_cache(maxsize=256) bounds _file_digests, _load_safetensors_state unifies safetensors checkpoint extraction across Hugging Face and timm providers, and LocalProvider caches pre-resolved submodule targets.
  • Fused RMSNorm and AdaptiveNorm kernels: RMSNorm.forward leverages native PyTorch C++/CUDA F.rms_norm with full float64 precision preservation, and AdaptiveNorm.forward combines F.instance_norm with torch.addcmul affine fusion, while un-fused mathematical formulations are retained in _reference(module) for reference validation.
  • Cached RoPE tables & causal mask simplification: Attention caches rotary position embedding tables per (positions, device, dtype) on a private instance cache to eliminate per-call tensor allocations and kernel launches, uses scalar-base exponentiation ROPE_BASE ** (-exponent), and constructs causal attention bias via torch.full((T, T), float("-inf")).triu(1).
  • Mixture of Experts sparse dispatch and 0-graph-break compilation: MixtureOfExperts.forward evaluates active routed tokens via sparse torch.where and in-place index_add_ in eager mode, and transitions to branchless dense scatter and unrolled accumulation during TorchDynamo tracing when torch.compiler.is_compiling() is true, achieving 0 graph breaks under torch.compile(..., fullgraph=True).
  • Separable 1D ragged adaptive average pooling: AdaptiveAvgPool2d.forward evaluates ragged 2D pooling via separable 1D window aggregation (_pool_axis along height then width), dropping kernel launches from $O(H \cdot W)$ (up to 73) down to $O(H + W)$ (at most 18) while maintaining bit-level deterministic parity.
  • Operator micro-optimizations: EqualLinear precomputes self._scale during initialization; Hopfield hoists transposed weight matrix access and prestores normalized shapes; FeedForward binds activation functions directly without lambda wrappers; PoolTokens binds the reduction callable at construction time; SpatialAttention and TransformerBlock fuse residual scaling and additions with torch.addcmul.
  • Operator relation deduplication: Extracted reusable non_image and reduce_axis relations, reused conv_axis and conv_output across pooling and resblocks, deduplicated eval_weight across equalized operators, and streamlined split and group_norm relations.
  • Per-sweep constraint solver convergence: _Solver.run validates convergence independently after forward and backward sweeps, terminating early when fixed points are reached to halve total solver sweeps from $4N$ to $2N$ on forward-resolved graphs.
  • Pre-allocated solver views and operator metadata: _Solver pre-allocates node views and port references once during initialization, and Operator.__post_init__ caches port lists, pattern entries, argument bindings, and dtype maps for $O(1)$ lookups.
  • $O((V+E)\log V)$ topological sorting: Kahn's algorithm in _ordered_nodes uses heapq and integer in-degrees to sort nodes deterministically with optimal asymptotic complexity.
  • Redundant validation skip in build(): ResolvedPlan tracks a validated stamp (id(registry), limits) set during resolve_graph or validate_concrete_plan, allowing build() to skip redundant validation passes when the plan is unchanged.
  • Plan digest caching & default settings singletons: ResolvedPlan.semantic_digest is cached upon post-init; default node initialization and trainability use frozen singletons (DEFAULT_INITIALIZATION, DEFAULT_TRAINABILITY) to eliminate repeated dictionary normalization and validation passes.
  • Registry and parser speedups: Registry.builtins() caches built-in definitions template for microsecond cloning, normalize_arguments() skips redundant validation of default arguments, and _parser.py fast-paths ASCII line locations and integrates AST depth tracking directly into the validator pass.
  • Compiler code readability and decomposition: Decomposed Capture.emit into _bind_inputs and _rethrow_with_source, decomposed _ordered_nodes into 4 cohesive functions, unified plan table rendering (format_plan_table) and shape formatting (format_shape), and isolated conv_axis argument unpacking.
  • Benchmark input generation consolidation: Unified random_inputs helper in tests/_network_examples.py supporting all tensor dtypes, bound integers, and gradient requirements, eliminating duplicated input generators across benchmark modules.
  • Benchmark warmup and device attribution: Added pre-measurement warmup passes to test_parity_vs_handwritten_pytorch.py to prevent JIT and cache compilation skew from contaminating timing runs, removed dead DEVICE constants, and tagged all benchmark metrics with explicit [{device}] labels for clear CPU/CUDA differentiation.
  • Testing infrastructure documentation: Authored TEST_INFRA.md formalizing the 4-tier testing hierarchy and mapping all 38 features from PROJECT.md, and certified test readiness in TEST_READY.md.

0.8.1 (2026-10-15)

  • Full E2E integration pass and test suite alignment: Verified 100% pass rate (122/122 passed) across all four tiers of the end-to-end audit remediation test suite in tests/e2e/test_audit_remediation_e2e.py, aligning test expectations for statement unpacking chains, ambiguous interval reporting, and pattern rank underflow diagnostics with production solver semantics.
  • Source distribution fixture inclusion (H-07): MANIFEST.in includes CHANGELOG.md, src/hndl/py.typed, and recursive test JSON fixtures (recursive-include tests *.py *.json), ensuring running pytest against an unpacked sdist finds all 0.6.0 plan compatibility fixtures.
  • Specification and implementation catalog synchronization (H-08): Synchronized IMPLEMENTATION.md and SPEC.md to document the 69 built-in operators across 12 categories, documented random initializers under torch_default@2, documented Arg.since in SPEC.md, and added synchronization tests in tests/test_package.py.
  • Pretrained intermediate activation capture semantics (L-07): Documented forward hook capture mechanics, multi-layer extraction, automatic tensor cloning guards against downstream in-place operations, early forward termination, and full autograd preservation in docs/pretrained.md.
  • Operator documentation and benchmark comment hygiene (L-09): Added scripts directory to the ruff check checklist in docs/ADDING_OPERATORS.md, and updated outdated "torch 2.14" references in benchmark test comments to "PyTorch 2.6+" / "torch 2.x".
  • Pytest directory recursion exclusion and git cleanup (L-10): Configured norecursedirs = [".*", "build", "dist", ".claude", ".agents"] under [tool.pytest.ini_options] in pyproject.toml, pruned 28 stale git worktree registrations, cleaned .claude/worktrees/, and safely deleted 74 merged local branches.
  • Resolved plan representation and operator positional argument validation (M-10): ResolvedPlan.__repr__ differentiates unary sequential chains (displaying index, single input shape, and single output shape columns) from branched multi-input/multi-output graphs (omitting index, displaying full input/output shape columns with port reference names p=ref:[...]), aligning plan printing with GraphModule.__repr__. make_operator and Operator.__post_init__ strictly enforce that operators declaring positional_rest have no positional=True arguments, and Operator.positional_names returns an empty tuple () when positional_rest is set.
  • Public API typing and PEP 561 compliance (M-11): Added src/hndl/py.typed marker package, enabled from __future__ import annotations across core modules, replaced untyped : object signatures in types.py and operator.py with concrete type hints, and fully typed public entrypoint functions (resolve, resolve_file, network, network_file, network_from_callable, build, parameter_counts).
  • CI isolation, benchmark fixture alignment, and documentation links (M-14): Isolated wheel testing directory inside $RUNNER_TEMP in .github/workflows/publish.yml and added a dedicated sdist unpack and test step; added develop branch to on.push.branches in .github/workflows/ci.yml; wired device fixture across benchmark tests and aligned HandwrittenTransformerBlock in test_parity_vs_handwritten_pytorch.py to use 3 separate Linear projections and F.scaled_dot_product_attention matching Attention; intercepted production URLs in scripts/gen_doc_pages.py to map to internal Markdown targets.
  • RMSNorm double-precision preservation (H-06): RMSNorm.forward preserves float64 precision when running double-precision inputs instead of downcasting to float32, ensuring exact parity against F.rms_norm and passing torch.autograd.gradcheck.
  • RoPE double-precision calculations (M-12): attention._rope_tables calculates frequency exponents, inverse frequencies, and angles in float64 when dtype=torch.float64, preventing numerical noise and precision degradation during double-precision attention evaluation.
  • PosEmbed sequence length bounds validation (M-12): PosEmbed.forward validates that input sequence length does not exceed max_len, raising HNDLError("E_CONSTRAINT") instead of silently broadcasting position 0 across longer sequences.
  • Dense Mixture of Experts reference oracle (M-12): MixtureOfExperts._reference provides an independent dense oracle computing functional linear projections and dense gate softmax weighting across all experts without sparse indexing or submodule dispatch.
  • Builtin operator reference functions (M-13): All 19 non-pretrained operators lacking mathematical references (adaptive_norm, add, chunk, cls_token, concat, conv, coordinate_grid, deconv, flatten, fourier_features, grid_sample, group_norm, leaky_relu, linear, pos_embed, relu, reshape, split, tanh) now provide exact reference= implementations, achieving 100% reference coverage across all 68 non-pretrained builtin operators.
  • Dedicated operator test modules (M-13): Added 15 comprehensive unit test suites in tests/operators/ covering shape propagation, autograd gradients, numerical parity vs reference implementations, dtypes, and error cases for all previously missing operator modules.
  • Chunk initialization cleanup (L-07): Removed dead self.size attribute and unused *, input_shapes parameter from Chunk.__init__, allowing direct instantiation without requiring dummy shape dictionaries.
  • GridSample positional argument alignment (L-07): Optional arguments mode, padding_mode, and align_corners in grid_sample are configured with positional=False and provided with default parameter values in GridSample.__init__.
  • Spatial operator and linear layer representations (L-08): Added comprehensive extra_repr() implementations to CoordinateGrid, FourierFeatures, GridSample, EqualLinear, and Attention (reporting equalized={self.equalized}).
  • ResBlock channel divisibility validation (L-08): ResBlock.__init__ validates that out_channels % groups == 0 when norm="group_norm" raising HNDLError("E_CONSTRAINT"), and supports direct construction with arbitrary extra kwargs.
  • TransformerBlock reference deduplication (L-08): transformer_block._reference deduplicates attention, normalization, and feed-forward math by delegating directly to the submodule reference implementations of Attention, FeedForward, LayerNorm, and RMSNorm.

  • Line break normalization (H-01): Declarative configuration sources now normalize \r\n (CRLF) and bare \r (CR) line endings to \n, ensuring valid line reporting and preventing unhandled IndexError in AST location mapping.

  • Token screener newline reset (H-02): Statement-level multi-output unpacking (e.g. (a, b) = split(...) or [a, b] = split(...)) across newlines no longer increments the operator nesting counter.
  • Empty tuple target rejection and tensor tuple locations (M-03): Empty tuple assignments (p = ()) are rejected with E_SYNTAX, and tensor tuple arity errors (E_OUTPUT_ARITY) report precise source line, column, and loop iteration diagnostics.
  • Declarative f-string rejection (M-04): Formatted string literals (f"...", F"...", fr"...", rf"...") are rejected during token screening before AST parsing with E_SYNTAX.
  • Loop collision diagnostic clarification (L-01): Duplicate node name collisions inside loops now distinguish whether the conflicting earlier node had an explicit name, an earlier loop suffix, or an auto-generated ID.
  • Explicit input dtype validation (M-05): Falsy input_dtype values ("", False, 0, ()) are preserved and rejected with E_SCHEMA rather than silently coerced to float32.
  • External port name reservation checks (M-06): External port names matching Python keywords (for, def), loop iterator (range), initializer schemes (normal, uniform), or operator aliases are strictly rejected across Graph definitions, Capture, and resolve_graph.
  • Callable capture diagnostic attribution (L-02): Errors raised during callable capture (argument validation, port binding, and initialization) preserve explicit node names (node=) in diagnostics.
  • Container type validation (L-05): Example.input_shape/output_shape and Node.args/inputs/outputs validate container types and protect against accidental string slicing or key-dropping.
  • Ambiguous solver interval reporting (M-07): When an ambiguous port has both collapsed and open interval constraints across different axes, E_AMBIGUOUS reports the open interval rather than the collapsed interval.
  • Ellipsis rank underflow port attribution (L-03): In _Solver.patterns, rank underflow when expanding ellipsis patterns directly attributes the port whose measured rank underflows the pattern rank.
  • Defensive bounds checks in solver and relations (L-04): _Solver.axis and _Solver.interval bounds-check axes to guard against negative axis aliasing and IndexError; conv_input_range returns empty interval (1, 0) on non-positive extents; conv_transpose_input returns None when mathematically unreachable; conv_axis verifies valid axes and guards against None context.
  • Chain classification and slice step validation (H-03): _is_chain now verifies tuple(node.outputs) == ("out",) so single-output tuple-returning operators (chunk(1)) are not misclassified as unary chains, and GraphModule.__getitem__ strictly rejects non-unit slice steps (step != 1) with ValueError.
  • Pre-forward state verification on compile path (M-08): GraphModule._execute now verifies registered state matches the build before executing forward when torch.compiler.is_compiling() is active, preventing TorchDynamo tracing crashes and misattributed mutations.
  • Fast-path cache invalidation on shallow copy and submodule mutation (M-09): GraphModule._apply now clears self._validated in place, ensuring that casting a shallow copy invalidates cached signatures on the original graph, and _record_stores/_execute tracks parameter/buffer dtypes and devices to prevent unhandled ATen errors upon submodule in-place casts.
  • Pretrained trainable mode synchronization (H-04): GraphModule._build now calls submodule.train(submodule.training) after unfreezing parameters on trainable pretrained nodes, ensuring the wrapped model starts in training mode rather than lingering in frozen evaluation mode.
  • TimmProvider Hub revision forwarding (H-05): TimmProvider.instantiate forwards self.source.revision as f"{model_name}@{revision}" for Hugging Face Hub (hf://) sources, and TimmProvider.__init__ accepts default component="" and falls back gracefully to architecture in source.config.
  • Pretrained checkpoint cache invalidation and weight hashing (M-01): resolve_source separates Hub checkpoints from local files/directories using file modification timestamps (st_mtime_ns) and sizes in the cache key, and includes weights SHA256 digests in bare .safetensors and directory checkpoint revisions, invalidating traced output shapes and catching in-place weights mutations without requiring manual cache clears.
  • Pretrained error handling and dependency guards (M-02): Corrupted or non-UTF-8 config.json files and unreadable weight files are caught and raised as structured HNDLError("E_PRETRAINED") rather than raw JSONDecodeError, UnicodeDecodeError, or OSError; TimmProvider.instantiate verifies safetensors availability before loading checkpoint weights.
  • Meta-device view storage deduplication (L-06): _state_bytes now keys meta-device storages by (value.device, storage._cdata) rather than id(value), accurately deduplicating storage footprints for parameter and buffer views on meta devices.

0.8.0 (2026-09-26)

A minor release for operators defined outside HNDL: ops calls operators registered on the capture's registry, shape relations are public in hndl.relations, and hndl.testing runs the built-in operator harness on host operators. The forward fast path also notices parameters, buffers, and submodules that were deleted, cleared, or added without a registration hook.

  • ops calls custom operators. Inside resolve_callable or network_from_callable, the global from hndl import ops now looks each alias up in the registry that capture runs under, so an operator registered on it is called as ops.my_op() instead of failing with E_OPERATOR. registry.ops.my_op() still works and mixes freely with ops in one capture. Outside a capture ops still checks aliases against the built-in catalog, and a factory read there resolves its alias when it is called.
  • A factory from another registry fails with E_CAPTURE. Calling other.ops.my_op() in a capture whose registry does not hold that exact declaration used to fail with E_STATE_VERSION; it now fails with E_CAPTURE, naming the operator and saying which registry to pass. The same identity declared by a different class in the capture's registry is rejected the same way instead of being accepted. Built-in factories from any Registry.builtins() keep working in every built-in registry, which shares their declarations. The message suggests ops.<alias> only when the capture's registry binds that alias to the same identity, and otherwise names the operator the alias binds there.
  • hndl.relations is public. The convolution arithmetic, the 2D convolution relation, elementwise joins and broadcasting that the built-ins use in relation= functions move from the private hndl.operators._relations to a documented module, joined by conv_input_range, conv_transpose_input and the per-axis relations conv_axis and conv_transpose_axis for operators with their own strided axes. The old import path re-exports them. The per-axis relations fail with E_CONSTRAINT when a port's rank has no such axis.
  • hndl.testing is public. The harness every built-in operator passes, check_operator(registry, alias), runs on any registry: declaration completeness, then for every example on every available device the frontend and JSON round trip, build, forward and backward, reproducible rebuild and reference comparison, plus float16 and bfloat16 on CUDA. check_declaration, check_round_trip, check_build_and_run and check_reference run one check each, and example_params and operator_params build pytest parameters for them. The built-in suite now runs through it. Importing hndl or hndl.testing does not import pytest. A check fails with AssertionError, except where HNDL itself rejects the example while resolving, building or running it, such as E_RUNTIME for a module whose output shape differs from its declaration. devices and dtypes take one name or a list, and the class must carry its own docstring rather than inherit one.
  • docs/ADDING_OPERATORS.md covers operators declared outside the package: calling them through ops, reusing hndl.relations in a strided operator's relation, testing them with hndl.testing, and adding arguments with Arg(since=...).
  • Registered-state edits PyTorch runs no hook for are caught on the next call. del module.weight, linear.bias = None and direct writes to a module's _parameters, _buffers or _modules used to go unnoticed on the unchecked path until a new input signature, a move or cast, or a failing layer forced a full check, so a layer could silently run without its bias. Each call now compares, in C, which names those mappings hold, which of them are None, and which submodules, with a record taken when the state last matched the build: about 0.7 us per call for a five-node MLP and 1.3 us for a transformer block. An entry removed, set to None or added, or a submodule replaced, fails the next call with the same E_RUNTIME report as a registration, naming the node and what changed. A tensor swapped in under a registered name is not a change, so torch.func.functional_call stays on the unchecked path, and the record holds no tensors, so nothing a functional call passed in is kept alive or reaches copy.deepcopy. Not detected: a whole mapping replaced, a mapping reordered, one name removed and another added in the same _parameters or _buffers between two calls, and a submodule replaced by one that compares equal to it.
  • The forward-latency parity benchmark (-m benchmark) allows hndl 1.5x hand-written PyTorch for the MLP and transformer block, down from 2.0x, and compares the fastest of ten interleaved rounds per side instead of one sequential mean each. The convolution case keeps 2.0x: its ratio swings with machine load and cannot see per-call overhead.

0.7.0 (2026-09-26)

A minor release: configs repeat blocks with bounded for _ in range(N): loops, networks check their contracts once per input signature instead of on every call, config parsing runs in process, saved plans stay loadable as operators gain arguments, and new equalized-learning-rate and coordinate-rendering primitives join the catalog.

  • Configs can repeat statements with for _ in range(N):. N is a positive integer literal, loops nest, and the body takes any top-level statement, so h = add(h, feed_forward(layer_norm(h), 512)) in a loop stacks residual blocks. A loop builds exactly the nodes, plan, semantic digest and state_dict() keys of the statements written out by hand. name="block" inside a loop becomes block0, block1, ...; nested loops append every index, outermost first (res1_3). There is no loop variable, arithmetic or conditional: other targets, range forms, while, break, continue, if, comprehensions and _ as a value fail with E_SYNTAX, and index-dependent structure belongs in native Python. A loop that would unroll past max_nodes, or loops nested more than 8 deep, fail with E_RESOURCE before any node is created. Configuration, resolution and runtime errors about an unrolled node report the iteration, as in line 12, column 5, iteration 3 of 8, from new iterations node source metadata. range is now a reserved operator alias in configs. The ViT and GPT example networks use loops for their blocks.
  • Config parsing runs in process. The AST allowlist is unchanged and source is still never compiled or executed, but the python -I -S worker, its JSON wire protocol and its limits are gone. Parsing a small config drops from about 32 ms to under 0.2 ms, and it no longer requires Linux. Source stays capped at 64 KiB. Before ast.parse runs, the token stream is screened for bracket nesting past 50 levels and more than 32 Python operators or keywords (valid configs use none), because on CPython 3.11–3.13 deeply chained expressions crash ast.parse on a small thread stack instead of raising; such input now fails with E_SYNTAX or E_RESOURCE. The per-literal, line-count, AST-node and integer-bit limits are dropped: the source cap and each operator's argument schema already bound those values.
  • Restoring a plan explains a mismatch, and fills values the plan already determines. E_INTEGRITY from revalidation lists every differing port shape and argument per node. A plan missing only an operator default (saved before the operator gained that argument, like pretrained plans from before layers=) or an argument bound to a saved port dimension now loads completed, with a warning naming what was filled and the new semantic digest. A missing value only a policy or relation search would choose is still refused. Digest mismatches now say the file is corrupted or was edited by hand.
  • The default max_state_bytes rises from 1 GiB to 64 GiB. The old default refused to build a GPT-2-medium-sized network (405M parameters, 1.6 GB); the new one still catches a typo that asks for a huge model before allocating. ResolvedPlan.from_json drops its 16 MiB input cap and duplicate max_nodes check; revalidation still applies max_nodes.

  • Contracts are checked once per input signature, not on every call. The first forward whose inputs have a given shape, dtype and device (in a given training mode and autocast state) still checks every node's ports and that no module created or removed registered state; later calls with the same signature compare only the inputs and run the layers back to back. Moving or casting the model, or registering a parameter, buffer or submodule on any of its modules, makes the next call check everything again. The fixed per-call cost of a five-node MLP drops from ~30-40 us to ~6-9 us: at batch 32 it runs ~1.2x hand-written PyTorch instead of ~1.8x. Errors say more: E_RUNTIME names the node, its operation and source line, and prints the contract in HNDL notation beside the tensor that arrived (expected [B=32, 64]:float32 on cpu / got [32, 63]:float32 on cpu); dtypes are spelled float32, not torch.float32. An exception raised inside a layer keeps its type, message and traceback (a RuntimeError or out-of-memory error is still caught as one) and gains a note, via add_note, naming the node, its operation and source line, its inputs against their contract, and any registered-state change that explains it; an exception passing out through nested graphs carries only the innermost node's note. Registered state edits PyTorch runs no hook for --- del of a registered name, module.param = None, direct writes to _parameters/_buffers/_modules --- are reported at the next full check or when a layer then fails, not on the very next call.

  • Add broadcast_mul, coordinate_grid, fourier_features, and grid_sample for style-conditioned coordinate renderers composed in HNDL. Fourier tables and coordinate grids are persistent buffers; sampling follows PyTorch semantics.

  • Add opt-in equalized=True to linear, attention, and feed_forward: raw N(0,1) weights, zero biases, and runtime 1/sqrt(fan_in) weight scaling with unit gain and learning-rate multiplier. Existing defaults, shapes and parameter names stay unchanged. Initializer overrides target raw weights; equalized linear rejects combination with spectral normalization.

  • Saved plans stay compatible when an operator gains an argument. Arg accepts since="<release>" for an argument added to an already released operator. A resolved node that holds such an argument's default omits it from its args and argument origins, and module construction fills it back in. equalized is declared this way, so plans saved by 0.6.0 load again (they failed with E_INTEGRITY), and any plan that does not set equalized=True encodes and digests byte for byte as in 0.6.0. Writing equalized=False explicitly is the same plan as omitting it.

0.6.0 (2026-09-21)

A minor release adding TransGAN-style relative-position-bias attention and selectable random initializer schemes, plus a forward-pass performance pass.

  • init= selects random initializer schemes, not just constants. An entry in the per-parameter init mapping may now be one of eight keyword-only scheme calls instead of a number, mixed freely with constants in the same mapping:
linear(init={"weight": xavier_uniform(gain=1.0), "bias": 0.0})
attention(4, init={"relative_position_bias_table": truncated_normal(std=0.02)})
conv(64, kernel_size=3, init={"weight": kaiming_normal(mode="fan_out", nonlinearity="relu")})

The schemes are xavier_uniform(gain=1.0), xavier_normal(gain=1.0), kaiming_uniform(a=0.0, mode="fan_in", nonlinearity="leaky_relu"), kaiming_normal(a=0.0, mode="fan_in", nonlinearity="leaky_relu"), truncated_normal(mean=0.0, std=1.0, a=-2.0, b=2.0), normal(mean=0.0, std=1.0), uniform(a=0.0, b=1.0) and orthogonal(gain=1.0) --- each one the torch.nn.init function of the same name, with torch's own keyword names and defaults, so truncated_normal(std=0.02) is torch.nn.init.trunc_normal_(parameter, mean=0.0, std=0.02, a=-2.0, b=2.0). mode is fan_in or fan_out and nonlinearity is one of the names torch.nn.init.calculate_gain accepts; every other keyword is a number rounded to float32 exactly like a constant override. Fills happen inside the construction RNG scope, in module-parameter order and then node order, so the same plan and the same initialization_seed reproduce them bit for bit. Xavier, Kaiming and orthogonal need a parameter of at least two dimensions: linear(2, init={"bias": xavier_uniform()}) is E_INITIALIZATION naming the parameter and its shape, checked before any node is initialized rather than surfacing a raw torch ValueError.

  • The same initializer names work in native Python. from hndl import xavier_uniform (or from hndl.initializers import ...) gives plain functions returning the record the declarative parser builds, so ops.linear(init={"weight": xavier_uniform(gain=1.0)}) and linear(init={"weight": xavier_uniform(gain=1.0)}) resolve to the same semantic_digest. The eight names are reserved: registering an operator alias that shadows one is E_REGISTRY, and a parse request carrying one is E_NAME.

  • Grammar: calls stay out of literal containers, with one narrow exception. An initializer call is legal only as a direct value of an init={...} mapping on an operator call. A bare init=xavier_uniform(), a scheme in a list, a scheme nested inside another scheme's arguments, a scheme in trainable={...} or in any other keyword's dictionary, and any non-initializer call inside a literal container all remain E_SYNTAX, rejected by the isolated AST validator before any operator lookup happens.

  • Plan format: initialization.kind gains torch_default@2. A node with at least one scheme override records {"kind": "torch_default@2", "overrides": {"weight": {"kind": "xavier_uniform", "gain": 1.0}, "bias": 0.0}}. Constant-only nodes --- including the empty default --- keep emitting "torch_default@1" unchanged, so every plan written before this release keeps its exact bytes, semantic digest and artifact digest. Both versions are accepted on restore forever; a scheme record under "torch_default@1", a "torch_default@2" record with no scheme, a missing or extra scheme keyword, and a non-canonical float32 scheme argument are each E_INITIALIZATION.

  • attention learns a 2D relative-position bias. With attention(4, spatial_shape=(16, 16), relative_position_bias=True) the [B, T, D] sequence is read as a row-major H x W token grid --- token t sits at row = t // W, col = t % W --- and each head learns one bias per query-minus-key offset, the Swin/ViT/TransGAN construction. The learned parameter is relative_position_bias_table, of shape [(2H-1)*(2W-1), heads], gathered through a precomputed [T, T] index into a [heads, T, T] bias that is added to the scaled logits before the softmax. The bias reaches the kernel as an additive attn_mask, so scaled_dot_product_attention still picks a fused kernel; with causal=True as well, the causal -inf mask and the bias are summed into one additive mask rather than handed to the kernel separately. The table is constructed at 0.0, so the layer starts as ordinary attention, and construction overrides target it by name (init={"relative_position_bias_table": 0.02}, trainable={"relative_position_bias_table": False}). The index is a non-persistent int64 buffer rebuilt from spatial_shape, so it stays out of checkpoints. H*W must equal T: a grid that does not cover the sequence is E_CONSTRAINT at resolution rather than a silent broadcast, and relative_position_bias=True without a positive spatial_shape --- or a spatial_shape without relative_position_bias=True --- is E_ARGUMENT. The operator carries no windowing of its own: partition a map into windows with chunk, reassemble it with concat, and give the node the (H, W) of one window.

  • attention gains per-projection bias flags. qkv_bias and out_bias narrow the existing bias flag: q_proj, k_proj and v_proj carry a bias when bias and qkv_bias, and o_proj when bias and out_bias. Both default to True, so bias= on its own behaves exactly as it did --- one flag for all four projections --- while attention(4, qkv_bias=False, out_bias=True) gives the unbiased query/key/value projections with a biased output that ViT-style blocks use. A projection built without a bias has no bias parameter at all, so its state_dict is unchanged from bias=False.

  • Plan format: attention nodes carry four more arguments. qkv_bias, out_bias, relative_position_bias and spatial_shape are concrete on every resolved attention node, so a plan saved by 0.5.0 that contains an attention node no longer matches its own digest and must be re-resolved from its configuration; the configuration itself is unchanged. Plans without an attention node encode and digest exactly as they did.

  • Faster forward passes. GraphModule no longer re-derives its per-call constants on every call. Contract shapes are parsed once at build time and resolved against a concrete batch only when the batch size or the runtime dtype changes, and each node's module handle, port labels and expected shapes are baked into a flat program instead of being rebuilt from f-strings and ModuleDict lookups per call. The fixed per-node overhead drops from about 13 us to about 5 us on the reference machine: in tests/benchmark/test_parity_vs_handwritten_pytorch.py the MLP's parity ratio against hand-written PyTorch improves from 1.41x to 1.19x at batch 256 and from ~2.5x to ~1.6x at batch 32, and transformer_block from ~1.44x to ~1.29x. Validation is unchanged: every shape, dtype and device check still runs on every port of every call, in the same order, with the same E_RUNTIME messages.

  • The forward-time state-integrity check replays a recorded walk. The check that catches a module creating or removing registered state mid-forward used to rebuild every dotted parameter and buffer name by recursing through the module tree on each call. It now records that walk once at build time — the modules it visited, each one's child mapping, and the registration keys each one contributed — and replays it against that flat list, comparing key tuples instead of formatting names. Pinning each visited module's _modules mapping by key and by child identity is what makes the flat list safe: nothing can be grafted into the tree unseen, so the recorded visit order and every module's path are still the ones the dotted names were built from. None slots and tensors already seen earlier in the walk are filtered exactly as named_parameters and named_buffers filter them. Detection is therefore unchanged from 0.5.0 — including a forward that fills a declared-None parameter, buffer or submodule slot (the lazy-initialization bug, where build() hands the caller an empty parameters() and the real weights appear on the first call, never trained, never seeded, and absent from the checkpoint the plan describes), a submodule swapped out under an unchanged attribute name, and a parameter dropped with self.weight = None — except in one case, where it is now stricter: attaching, detaching or swapping a submodule that registers no parameters or buffers of its own contributes no dotted name, so 0.5.0 let that through and this check reports it. As in 0.5.0, registering an already-registered tensor under a second name is not reported, because de-duplication drops the alias from the old name tuple and the new key tuple alike.

0.5.0 (2026-09-21)

A minor release adding a first-class spatial_attention operator and an opt-in performance/optimization test suite.

  • Opt-in performance/optimization tests. tests/benchmark/, marked benchmark and excluded from CI (pytest -m "not network and not benchmark"), times every network in examples/networks end to end, checks whether torch.compile accepts each built graph and by how much it speeds inference up, and asserts hndl's built graphs run within a bounded multiple of hand-written PyTorch equivalents. Run explicitly with pytest -m benchmark tests/benchmark.

  • spatial_attention operator. The SAGAN self-attention block (Zhang et al. 2018) as one first-class operator over [B, C, H, W] feature maps: 1x1-conv query/key/value projections, a softmax attention map over flattened spatial positions, and a zero-initialized learned_scale gate on the residual, all in one node instead of eight. examples/networks/sagan_attention.hndl now calls spatial_attention() instead of composing it by hand.

0.4.0 (2026-09-21)

A minor release for batch-axis joins: concat joins tensors along the batch axis with the multiple tracked as k*B, and a new chunk operator cuts an axis back into equal sections.

  • concat joins along the batch axis, tracked as k*B. axis=0 was rejected; it now stacks examples, so combined = concat(candidate, context, axis=0) turns two [B, C, H, W] tensors into one [2*B, C, H, W] and a shared --- often frozen --- network sees both branches in a single forward pass. Batch stays symbolic: an intermediate contract carries the entry "2*B", meaning two of the plan's batches, and the resolver tracks it separately from "B" everywhere --- through ordinary operators, through pretrained (including layers=), in the saved plan, and in the runtime shape check, which requires k times the batch of the call. The sum runs both ways, so 2*B + B is 3*B and one unknown input batch is solved from a known total. External input_shape and output_shape contracts stay one plan batch (E_SCHEMA), so a graph chunks a joined tensor back before publishing it.

  • New chunk operator: one axis into equal sections. a, b = chunk(x, 2) halves a feature axis and a, b = chunk(features, 2, dim=0) takes a 2*B tensor back apart into two B tensors, the inverse of the join above. It produces exactly chunks outputs (1 <= chunks <= 32), returns a tuple and clears the current tensor like split, and its sections are views, so first and second derivatives reach the input through every one of them. Uneven divisions fail at resolution with E_CONSTRAINT rather than at a runtime that would only ever see one batch size: an extent of 5 into 2 sections, a 2*B batch into 3, and a plain B batch into 2 are all rejected when the plan is resolved. chunks=1 is allowed and returns a one-tuple, matching pretrained(..., layers=("layer1",)).

  • Plan format: existing plans are byte-identical. Batch multiples have one spelling each --- "1*B", "0*B", "B*2" and leading zeros are rejected with E_SCHEMA --- and "B" keeps its own, so every plan that does not join or divide the batch axis encodes and digests exactly as it did in 0.3.0. No existing digest changes. A saved plan's internal port contracts may now carry "k*B" for 2 <= k <= 1024; external contracts may not.

  • outputs_from= accepts an int argument. A variadic output port could only take its count from the length of a sequence argument; it now also accepts a bounded int argument, which is what chunk's chunks is. Operators declare how they treat axis 0 with batch="shared" (the default: batch passes through every port) or batch="relation", and a relation can read and set batch entries with s.batch(port) and s.share_batch(*ports).

0.3.0 (2026-09-21)

A minor release for multiscale feature extraction: one pretrained forward pass returns several intermediate layers, operators may declare variadic output ports, and .hndl files count as Python on GitHub.

  • Several layers from one pretrained forward pass. A provider checkpoint can now return more than one intermediate tensor: f1, f2, f3 = pretrained("trunk.pth", provider="resnet18", sha256="<64 hex>", layers=("layer1", "layer2", "layer3")) gives the node one output per entry, in the order written, each the raw output of that submodule at its native shape --- no pooling, no concatenation --- from a single forward pass that stops after the last requested submodule, so the tail of the network never runs. Every output carries gradients and second derivatives to the network's input: each captured tensor is cloned, so an nn.ReLU(inplace=True) or a residual += later in the pass can neither overwrite the values the hook saw nor break backward through them. Both frontends unpack the tuple, which clears the current tensor as split does, including for a one-entry layers=("layer1",); an empty layers=() means the argument was not given. Duplicate, empty, or unknown entries, a submodule that runs more than once before the pass stops, and a conflict with layer= or readout= each fail with E_PRETRAINED. Because plan digests cover every canonical argument, a plan saved before this release that holds a pretrained node fails to restore with E_INTEGRITY and must be re-resolved once from its source; plans without a pretrained node are unaffected.
  • Operators may declare variadic output ports. A shape declaration can write out* after the arrow together with outputs_from="<argument>", and the node expands ordinal ports out0, out1, ... from that sequence argument's length, mirroring the x0, x1 expansion of variadic inputs. An empty sequence leaves the single declared out port, so such an operator's existing plans keep their encoding and digests. Arg also gains a "strs" type: a bounded tuple of strings, written as a tuple literal in configuration.
  • .hndl files count as Python on GitHub. A .gitattributes at the repository root maps *.hndl to Python, so Linguist includes network definitions in the repository's language statistics.

0.2.1 (2026-09-21)

A patch release: cast networks check inputs in the dtype they were cast to, and provider checkpoints read tensors through host-registered readouts.

  • Networks follow .double(), .half() and .to(dtype=...). Casting a built network casts its parameters, and now its runtime contract as well: a network cast to float64 accepts float64 inputs and returns float64 outputs, and .float() puts it back. Graphs without parameters follow the cast too. Integer and boolean ports --- token ids, masks --- keep the dtype the plan declared, because those casts leave non-floating state alone. Copies made with copy.deepcopy carry the dtype the original was cast to, and casting a copy leaves the original alone.
  • Named readouts for provider checkpoints. A .pth checkpoint whose useful tensor comes from a method rather than forward — DINOv2's forward_features(x)["x_norm_patchtokens"] or get_intermediate_layers(x, n=(2, 5, 8, 11), reshape=True, norm=True) — now names host code for it. registry.pretrained_provider(name, build, readouts={"patch_tokens": fn}) binds named callable(model, x) readouts to a provider (and registry.pretrained_readout(provider, name, fn) adds one later), which a network selects with pretrained("w.pth", provider="dino", sha256="<64 hex>", readout="patch_tokens"). Configuration still names only registered code, so the plan stays a serializable string. The readout runs on the meta device while the plan resolves, so the node's output shape is inferred as usual; it must be a pure function of (model, x) returning exactly one tensor (concatenate or stack inside the readout, or register one readout per tensor). readout= and layer= are mutually exclusive, an unknown name lists the readouts the provider offers, and neither applies to transformers or timm checkpoints, which select output=.

0.2.0 (2026-09-21)

A feature release: networks copy with copy.deepcopy, graphs take named inputs and publish named outputs, GAN critics get spectral normalization and deterministic pooling, and local .pth checkpoints load through registered providers.

  • copy.deepcopy(model) works. A built network copies natively, which is what an exponential-moving-average model needs. The copy owns every parameter and buffer, keeps each requires_grad flag and the train/eval mode, and draws no random numbers; the resolved plan, its registry and the build receipt are immutable, so the copy shares them. copy.copy(model) is a second handle on the same tensors. Pickling a whole module still cannot work --- plans hold frozen mappings and operator declarations hold functions --- but it now says so and points at plan.to_json() plus torch.save(model.state_dict()) instead of failing inside the pickler.
  • broadcast_add operator. Elementwise sum of two equal-rank tensors with numpy-style broadcasting of size-1 non-batch axes, for per-sample, per-channel biases such as [B, C, H, W] + [B, C, 1, 1]. The backward pass reduces the broadcast axes with sum, so it is deterministic on CUDA. add keeps its exact-shape contract.
  • adaptive_avg_pool is deterministic and double-differentiable. When the input extents divide the output size it pools by reshaping and taking a mean over the window axes, and a ragged pool to at most 64 windows writes the windows out with slicing and stack. Both paths run under torch.use_deterministic_algorithms(True), give bit-identical CUDA gradients run to run, and support the second derivative a gradient penalty needs. Only a ragged pool to more than 64 windows still falls back to F.adaptive_avg_pool2d, whose CUDA backward is nondeterministic. Values, shapes, arguments, and the module repr are unchanged.
  • Spectral normalization. linear, conv, conv1d, and deconv accept spectral_norm=True, wrapping the weight with torch.nn.utils.parametrizations.spectral_norm for GAN discriminators. The learned tensor is then registered as parametrizations.weight.original, which is the name init and trainable overrides must target.
  • Local .pth checkpoints with custom providers. pretrained("weights.pth", provider="vgg16", sha256="<hex>", layer="features.16") loads a plain state_dict into an architecture the host registered with registry.pretrained_provider(name, build). Registration is trusted Python on one Registry instance; configuration may only name a provider that already exists. The digest is required and verified at resolution and again before loading, the file is read with torch.load(..., weights_only=True) and strict=True, and layer= returns an intermediate submodule's output through a forward hook that stops the pass there — what perceptual losses and feature matching need.
  • constant operator. Emits a [B, *shape] tensor filled with value (default 0.0), taking the batch extent and device from the incoming tensor and the compute dtype from the plan. It has no parameters and no buffers, its output is detached from the autograd graph, and the shape may be omitted and read from the output contract.
  • matmul operator. A batched matrix product of two rank-3 tensors, a[B, N, K], b[B, K, M] -> out[B, N, M], with both operands explicit. The shared inner dimension K flows in both directions; other ranks are rejected with E_CONSTRAINT, so reshape a [B, C, H, W] map to [B, C, H*W] first.
  • learned_scale operator. out = gamma * x with one learned scalar parameter named gamma, started from init_value (default 0.0, the SAGAN convention that makes a gated residual begin as the identity). Use scale for a fixed constant.
  • SAGAN self-attention example. examples/networks/sagan_attention.hndl builds the Self-Attention GAN block (Zhang et al. 2018) from registered operators alone: 1x1 projections, reshape/transpose, two matmuls around a softmax, and a learned_scale gate on the residual.
  • Named external inputs and outputs. input_shape and output_shape accept a mapping of named contracts — {"z": ("B", 128), "y": ("B", 10)} — in every resolve*/network* entry point, and input_dtype accepts one dtype per input. Declarative configuration prebinds each input as a local and selects each output by binding its name; a callable receives the inputs as keyword arguments and returns a mapping of named outputs. A network with one input and one output is unchanged, down to the saved plan's bytes.
  • Multi-output forward. GraphModule.forward(**inputs) accepts exactly the declared input names and returns a dictionary keyed by the declared output names. The network* facades accept the inputs positionally or by keyword and return a tensor for one output or that dictionary for several.
  • Conditional GAN example. examples/networks/conditional_discriminator.hndl takes an image and a label and publishes logits and features.

0.1.2 (2026-09-21)

README links are absolute so they work on the PyPI project page; a test keeps them that way. No library code changed.

0.1.1 (2026-09-21)

A documentation and packaging release. No library code changed.

  • Install from PyPI. The README now installs with pip install hndl and links to the documentation site.
  • DCGAN-style generator example. The transposed-convolution settings are spelled out instead of relying on policy="up2".
  • Documentation site. Published at https://hypergan.github.io/HNDL/, built with MkDocs and deployed from master by docs.yml.
  • Release workflow. PyPI publishing supports either an API token secret or Trusted Publishing.

0.1.0 (2026-09-21)

The first release of HNDL, the human-readable network definition language.

  • Operator declarations. Every operation is an nn.Module with an @operator(...) declaration: alias, summary, a shape relation written as a small DSL (x[B, ..., D_in] -> out[B, ..., D_out]) or a relation function, scalar arguments with help text, and runnable examples. Custom operators use the same decorator on a Registry. Documentation is generated from the declarations with python -m hndl.docs.
  • Catalog of 59 operators. Activations (gelu, silu, softmax, …), arithmetic and shape plumbing (add, mul, transpose, permute, mean, pad, …), normalizations (layer_norm, rms_norm, batch_norm, instance_norm, group_norm, adaptive_norm), convolution and spatial operators (conv, conv1d, deconv, pooling, upsample, pixel_shuffle, resblock, patch_embed), sequence operators (embedding, pos_embed, cls_token, attention, cross_attention, feed_forward, swiglu, transformer_block, pool_tokens, gather_token), moe, hopfield, and dropout. Convolutions gain the down2 policy, mirroring up2.
  • Sequences and dtypes. Rank-3 [B, T, D] tensors, plan dtypes float32, float16, and bfloat16, integer input ports (input_dtype="int64"), and edge dtype checking.
  • pretrained(source). Loads any checkpoint that transformers or timm can build from its configuration, from a local directory, a safetensors file, or hf://repo[@revision], as one frozen node whose output shape comes from a meta-device trace. Optional extra hndl[pretrained].
  • Authored networks. Complete configs for LeNet-5, DCGAN, U-Net, an autoencoder, ResNet-18, a tiny ViT and GPT, a Hopfield classifier, and a mixture-of-experts transformer under examples/networks, tested and rendered into docs/networks.md.
  • Backend. PyTorch is a dependency. Registered storage is bounded by an allocation-free meta-device pass before construction; the build receipt records the dtype and state bytes.
  • Removed. Registry.register, register_torch, ShapeRule, Dim, preserves_shape, and the per-node state_bytes/state_version plan fields from the 0.1.0a1 alpha.