Changelog¶
0.13.0 (2026-11-21)¶
- Enforce registered-state and mid-forward mutation checks on
PreparedNetworkgenerated execution with thread-safe signature updates, while reducing wrapper and generated-forward overhead so batch-1 CPU MLP execution beatsnn.Sequential. - Unify
InferenceCacheand streaming session guards into a single low-overhead traversal, reuse active device/stream/autocast context across layers, and addmul,mish,softplus, andclampto the streaming tokenwise contract. - Accelerate
GatedDeltaAttention(decay_kind="channel") via midpoint-shifted factored batched matmuls with overflow fallback and a directt=1recurrent decode fast path; preserveconv_q/conv_k/conv_vhooks and handleT=0inputs safely. - Vectorize
Mamba2chunked SSD evaluation, eliminate its redundantzxbcdtcopy, add a directt=1recurrent decode fast path, and upcastdt/A_logbeforesoftplus/expto preventfloat16overflow. - Fix
LatentAttention.absorb_weights()to avoid autograd graph leaks,inference_modecache crashes, and stale weights afterload_state_dict(); addunabsorb_weights(); replace absorbedeinsumcalls withmatmul/F.linear; enable FlashAttention on cached prefill; and packk_up/v_upprojections. - Eliminate per-token FlexAttention block-mask recompilation during single-token cached
Attentiondecode, bound_mask_cachememory by storing a single largest window mask per configuration, avoid caching inference tensors in_get_causal_bias(), and preserve autocast query/key dtypes inAttentionandLatentAttention. - Fix
MoEtorch.autocastdtype mismatches across grouped, padded, sparse, and fallback dispatch modes; eliminate redundant token gathers; single-pack padded execution; replacetile=1sparse fallback collapse with per-expert slicedF.linear; and packJointAttentionQKV projections. - Optimize
EqualLinear(scale smaller operand),RMSNorm(zero_centered=True)(fusedF.rms_norm),GRN(fusedaddcmul),HopfieldandSpatialAttention(gated SDPA),RoPE(pre-duplication trig),SinusoidalEmbed(cached fp32/fp64 frequencies), andDeploymentModel/export(pre-parsed input guards and single-pass direct-storage SHA-256 hashing). - Guard packed projection storage against
.weight.datareassignments withoutrebind_state(), and extendinit_policy="depth_scaled"to compositetransformer_block/resblockmodules and allmoeexperts. - Fix shape/argument validation and numerical edge cases in
transformer_block(head_dim, empty cachednode_id), 2D axial RoPE (head_dim % 4 == 0,H * W == T, NTK exponent, compiledstartslice),dy_tanh/drop_path/snake(rank-polymorphic resolution,bfloat16drop sampling,float16NaN and channel inference),deconv1d(causal=True),resblockbottleneckgroup_norm, andmatmul. - 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, andspatial_attention; completeplan.diff()for rewired inputs, initialization, trainability, and multi-output shape deltas; fix pass-through edges inplan.to_mermaid(); and remove O(N²) tie scans and redundant serialization inresolver.pyandtypes.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
cachealongside 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
--deviceoption 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
mastermirror 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
masterand 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.exportandload, 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
layerstwice. - 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), deferringnnimport toRegistry.subgraph, ensuring that importinghndldoes not eagerly load PyTorch intosys.modulesin clean Python processes.- PEP 562 Lazy Loading Tests: Added isolated subprocess verification tests to
tests/test_m5_tooling_lifecycle.pyandtests/e2e/test_v010_e2e.pycertifying thatimport hndldoes not introducetorchintosys.modules. -
resolver.pyPattern 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.pyiinterface stub forhndl.opscovering all 84 built-in operators with typed signatures and overloads, verified viapython -m hndl.docs --check. - PEP 562 Lazy Loading: Added module
__getattr__inhndl.__init__for lazy loading ofhndl.torchwithout eager torch imports. -
Manifest Exports: Exported
SymbolandNodeViewinhndl.__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()): RendersResolvedPlanas 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 (
hndlexecutable): Implemented command-line entrypoint withinspect(with--sidecar,--batch-size,--profile),mermaid(with--out), andchecksubcommands 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_matchessuggestions across operator aliases in parser and registry, arguments and policies innormalize_arguments, undefined variables inconfig.py, parameter targets in_prepare_parameter_settings, and node keys inGraphModule.__getitem__. - Operator Prefix Diagnostic: Added explicit
.hndlsyntax diagnostic directing users to call operators directly withoutops.prefix. - Solver Shape Provenance: Implemented origin tracking in
_Solver, reporting establishing origin labels and full conflicting shapes inE_CONSTRAINTandE_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_constructorforembedding(dim),layer_norm(D,affine,bias), andrms_norm(D,affine), enabling zero-dependency standalone instantiation and execution.codegen.pySubgraphs & Custom Modules: Appliedtextwrap.dedentto extracted custom module class sources; cleanly embedded composite subgraphs (Registry.subgraph) as standaloneSubmodel_<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 thannon_discard[0].-
_parser.py&config.py: EnforcedE_BINDINGrejection 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:
.hndlConstants: 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..hndlDef Macros: Added non-recursive AST-expanded macro definitions (def name(params): ... return out) with parameter substitution, statement budgets, and automatic unique scoped node prefixes..hndlTuple 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): AddedRegistry.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 andmodel.rebind_state()method onGraphModuleto 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 thehndl.operatorsentry-point group. -
Milestone 3 Gate Iteration 1 Remediation:
joint_attention: Addedqk_norm="l2_norm"per-head L2 normalization in both module forward execution and independent reference oracle.mamba2: Addedchunk_sizeargument, implemented semi-separable chunked recurrence inforward()with safe intra-chunk masked decay and inter-chunk state propagation, added joint depthwise convolution over $[x_{ssm}, B, C]$, cleaned up deadd_has_biasargument, 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_relationensuring mismatched channel dimensions raiseE_CONSTRAINTduring graph resolution.rope: Updated shape contract tox[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.jsonand synchronized operator documentation. -
6 New Built-In Operators (expanding catalog from 78 to 84):
mamba2(ssd@1,sequencecategory): 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,sequencecategory): 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,activationcategory): Dynamic Tanh activation and normalization with learned scalar frequencyalphaand per-channel affinegamma/betascaling.drop_path(stochastic_depth@1,regularizationcategory): 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,corecategory): Ternary element-wise selectionout = torch.where(cond, a, b)with boolean condition enforcement (E_DTYPE) and bidirectional multi-port shape inference.snake(snake@1,activationcategory): 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_scalingin "none", "linear", "ntk", "yarn", "llama3"), scale factorrope_scale, 2D axial RoPE viaspatial_shape=(H, W), and rank-4[B, H, T, D_h]tensor support.attention&latent_attention: Forwardedrope_scaling,rope_scale, andspatial_shapeto internal RoPE and decoupled RoPE layers.resblock: Addedkind="bottleneck"(3-convolution residual bottleneck with expansion ratio) and configurableactivation("relu", "silu", "gelu").transformer_block: Added decoupledhead_dim,window_sizesliding-window local context masking,logit_softcap,qkv_bias,out_bias,zero_centeredRMSNorm, andpost_normPost-LN architecture layout.deconv1d: Addedcausal=Truezero-lookahead left-padded transposed 1D convolutions andchannels_last=True[B, T, C]layout support.adaln_zero: Addedgate=Falsesupport emitting a singleoutport with 2D (shift, scale) modulation without redundant residual gating parameters.moe: Addedrouted_scaling_factorparameter scaling routed expert outputs for DeepSeek-V2/V3 alignment.conv&conv1d: Addedpolicy="same3"andgroups="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)acrossoperator.py,resolver.py,reshape.py, andpermute.py, enabling native 5D video tensor[B, C, T, H, W]contract resolution and permutation. - Added single negative dimension
-1support inreshape(shape)at any non-batch position, inferring unknown dimension vias.product("x", "out"). - 4 New Authored Network Recipes (expanding recipe catalog from 21 to 25):
- Added
convnext_v2_tiny(.hndland.json, 77,900 parameters) exercising Global Response Normalization (GRN), DropPath stochastic depth, depthwise convolution, and learned residual scaling. - Added
encodec_autoencoder_tiny(.hndland.json, 83,009 parameters) exercising causal 1D strided convolution, periodic Snake activation, and causal 1D transposed convolution. - Added
clip_dual_encoder_tiny(.hndland.json, 89,920 parameters) exercising QuickGELU, cls_token, gather_token, L2 normalization, matrix multiplication, and scale. - Added
nerf_coord_field(.hndland.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, andtests/test_package.py. -
Scaled network example test suite
tests/test_network_examples.pyacross all 25 recipes. -
gated_delta_attentionnon-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 moe16-byte stride alignment & float16 compilation stability: Enforced 16-byte row stride alignment checks across both CPU and CUDA inMixtureOfExperts, routing unaligned byte layouts cleanly to batchedbmmfallback; undertorch.compile, restrictedtorch._grouped_mmdispatch tobfloat16and routedfloat16tobmmto prevent DynamoFakeTensormeta registration errors on CUDA < 13.3 or pre-Hopper/SM < 90 devices while maintaining 0 graph breaks.gated_delta_attentionempty batch ($b=0$) & backward numerical stability: Replaced ambiguous-1dimension with deterministiclog_alpha.shape[-1]in chunk reshaping to support empty-batch inputs ($b=0$) with full autograd graph preservation; lowered single-precisionmax_neg_expclamping threshold from $85.0$ to $45.0$ across full and tail chunk paths, completely eliminating float32 dot-product overflow into+infduring backward backpropagation and preventingNaNparameter gradients under strong decay rates.latent_attentionlinear bias rejection inabsorb_weights: GuardedLatentAttention.absorb_weights()to raiseHNDLError("E_UNSUPPORTED", ...)when projections contain linear biases, ensuring weight absorption is strictly applied to unbiased configurations without silent numerical drift.-
test_peak_memory.pywarmup pass for steady-state slot recycling: Added an explicit warmup forward pass before clearing cache and resetting peak memory stats intest_graph_module_dead_slot_clearing(), verifying steady-state slot recycling onGraphModule's compiled fast path. -
moegrouped GEMM & zero-sync sparse dispatch: Replaced eager Python expert loops and host-device synchronizations with token sorting viatorch.argsortand zero-sync grouped execution viatorch._grouped_mm(and batchedbmmfallback with zero Dynamo graph breaks undertorch.compile(..., fullgraph=True)), scaling with sparse $O(k)$ compute across expert counts. gated_delta_attention4D tensor core vectorization: Eliminated 5D tensor materializations in_chunk_forwardvia 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_attentionruntime optimizations: Added sliding-window and causal mask caching inAttentionandCrossAttention(with automatic cache invalidation on_apply()), eliminated tensor duplication on GQA soft-cap fallback paths via zero-copy broadcast views, eliminated redundanttorch.catallocations inLatentAttention, and added inference weight absorption (absorb_weights()) compressing KV representations by $5.7\times$.GraphModuledead activation slot recycling &build()fast path: Implemented immediate intermediate activation slot clearing (values[slot] = None) upon final consumer completion inGraphModule._executeto reclaim VRAM during deep network forward passes, optimized steady-state store checking via fast short-circuit comparison generators, and usedtorch.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.pybenchmarking forward + backward execution latency across all 21 example networks,tests/benchmark/test_peak_memory.pytracking peak activation memory and slot clearing efficiency, andtests/benchmark/test_sota_operators_latency.pybenchmarking sparse MoE scaling, GDA 4D chunkwise forward latency, MLA weight absorption, and GQA sliding-window attention. - Milestone 1 forensic bug remediation: Corrected
produced_is_computeport tracking inGraphModuleso floating-point module casts (.double(),.half(),.to()) track compute outputs accurately; revertedSinusoidalEmbed._applybuffer override to align module state bytes with build receipt while maintaining float32 precision during forward evaluation; and synchronizeddeepseek_moe_tinyparameter count assertion to 1,181,312. castruntime crash & buffer pollution remediation (B-01): Eliminated_prototypebuffer pollution from modulestate_dict()andbuffers()inCast, added"float64"toDTYPES, and updatedGraphModule._effective_dtypeto track compute-domain ports and leave explicit integer, boolean, and float64 ports unchanged under.half()or.to().torch.compileRoPE cache poisoning and device retention (B-02): Added cache clearing in_apply()acrossRoPE,Attention, andLatentAttentionmodules to eliminate device retention on.to(device)or.cpu(), bypassed caching whentorch.compiler.is_compiling()is true, and added max-length cache slicing for variable-length sequence evaluation.gated_delta_attentionfloat16 backward autograd stability (B-03): Evaluated log-space gating decaylog_alphaand recurrence accumulation incalc_dtype(float32/float64), preventing reciprocal/exponential overflow and subsequentNaNgradients during reduced-precision backward passes.grnandsinusoidal_embedfloat16 numerical precision (B-04): Evaluated spatial channel L2 norm in float32 withinGRNto prevent overflow on large spatial dimensions, and evaluated frequency angles in float32 while preservingfreqsbuffer precision across.half()inSinusoidalEmbed.matmul._relationrank inference monotonicity (B-05): Deferred rank guesses past Sweep 0 to maintain monotonic constraint narrowing and support backward rank inference from output contracts, and updatedMatmuldocstring 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 intervalss.interval("x", length_axis, (out_len - 1) * stride + 1, out_len * stride)instead of raisingE_AMBIGUOUSduring backward length resolution.pretrainednative registry contract & shape_fn support (B-07): Nativecontractandshape_fnsupport implemented directly inRegistry.pretrained_provider, eliminating monkey-patching inpretrained.py, inspecting signatures cleanly without trial-and-error exception swallowing, and guarding output port validation whencontract="ids".adaln_zerogate=Falsesupport and recipe alignments (B-08): Addedgateparameter toadaln_zerosupporting scale/shift modulation without residual gating, updateddit_tiny.hndlanddeepseek_moe_tiny.hndlrecipes 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 falseE_ASSIGNduplicate target errors, and omitted_from unrolled loop local variable bindings. l2_normdim validation,transformer_blockepspropagation &extra_repr(B-10): Validateddimbounds inl2_norm._relation, forwardedeps=epstoAttentionintransformer_block, and added informativeextra_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-4inmoesigmoid scoring, preventing reciprocal overflow to+infand subsequentNaNgradients during float16 backward backpropagation. - Numerical stability in MoE and Gated Delta Attention: Fixed float16 underflow in
moesigmoid scoring router andgated_delta_attentioncumulative decay, preventingNaNoutputs during reduced-precision evaluation. - Authored SOTA network recipes: Added 8 frontier neural network recipes with complete
.hndldeclarations and.jsonsidecars inexamples/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 throughpixel_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.pyacross 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, andtests/e2e/test_audit_remediation_e2e.py. conv1dcausal & sequence extensions: Addedcausal=Trueleft-padding with a bijective $L_{out} == L_{in}$ constraint solver relation whenstride=1, and addedchannels_last=Truefor direct[B, T, C]sequence evaluation.rms_normzero-centered scaling: Addedzero_centered=Trueinitializing weights to0.0and evaluating as $(1 + \text{weight}) \cdot \text{RMSNorm}(x)$ for Gemma-style models.layer_normbias-free option: Addedbias=FalsetoLayerNormfor constructing bias-free LayerNorm blocks.adaptive_normrank-3 sequence support: Extendedadaptive_normto accept rank-3 sequence tensors[B, T, C]alongside rank-4 image tensors[B, C, H, W].matmulmulti-rank batching: Generalizedmatmulto 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.moe3-projection SwiGLU experts, sigmoid scoring & bias toggle: Addedexpert_kind="swiglu"supporting 3-projection SiLU-gated feed-forward experts,scoring="sigmoid"for top-k normalized sigmoid router affinity, andbias=Falsefor unbiased expert linear projections.attentionGQA, QK-Norm, sliding-window & logit soft-capping: Extendedattentionwithkv_headsfor fused Grouped-Query / Multi-Query Attention (enable_gqa=True), decoupledhead_dimoverride, per-headqk_norm("rms_norm" and "l2_norm"),window_sizefor sliding-window local context masking,logit_softcapwith explicit tanh scaling fallback, and configurablerope_theta.cross_attentionGQA, decoupled head_dim, narrow biases & QK-Norm: Extendedcross_attentionwithkv_headsfor GQA, decoupledhead_dim, narrow projection bias controls (qkv_bias,out_bias), per-headqk_norm, andlogit_softcap.-
transformer_blockSwiGLU, explicit hidden width, RoPE & bias propagation: Extendedtransformer_blockwithffn_kind="swiglu"for 3-projection gated feed-forwards, explicit inner FFN widthhidden, forwardedrope,rope_theta,kv_heads, andqk_normto attention, and block-widebias=Falsepropagation. -
Pretrained provider contract hardening: Registered architecture providers on
registry.pretrained_providercan specify an optionalshape_fncallback to compute output shapes directly without executing on PyTorch'smetadevice (preventing crashes on custom Triton and CUDA kernels lacking fake-tensor registrations), and can declarecontract="ids"to consume rank-2[B, T]int64token IDs without triggeringE_DTYPE. castoperator & edge dtype propagation: Addedcast@1(corecategory) 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_normoperator: Addedl2_norm@1(normalizationcategory) providing parameter-free L2 normalization with configurabledimand numericaleps.grnoperator: Addedgrn@1(normalizationcategory) implementing ConvNeXt-V2 Global Response Normalization with spatial L2 channel pooling and zero-initialized recalibration parameters.sinusoidal_embedoperator: Addedsinusoidal_embed@1(sequencecategory) providing deterministic log-spaced sinusoidal timestep and coordinate embeddings.deconv1doperator: Addedconv_transpose1d@1(aliasdeconv1d,convolutioncategory) withup2policy and bidirectionalconv_transpose_axislength resolution.adaln_zerooperator: Addedadaln_zero@1(normalizationcategory) providing rank-3 adaptive LayerNorm-Zero conditioning modulation for Diffusion Transformers with zero-initialized linear projections.ropeoperator: Addedrope@1(sequencecategory) providing standalone rotary position embeddings for sequence tensors with configurableheadsand base frequencytheta.latent_attentionoperator: Addedlatent_attention@1(sequencecategory) implementing DeepSeek and Kimi Multi-Head Latent Attention (MLA) with low-rank KV compression, decoupled RoPE, and position-free NoPE mode.gated_delta_attentionoperator: Addedgated_delta_attention@1(sequencecategory) 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._executeimplements a 2-tier store verification fast path caching module and parameter IDs, validating steady-state forward passes in C without per-call tuple ortorch.deviceallocations (<1 µs onmlp, <10 µs onresnet18). - 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_programanalyzes 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.compiletracing:GraphModule._resolve_shapesavoids mutatingself._compiledduring TorchDynamo tracing, ensuring compile transparency and dynamic shape evaluation without cache interference. - Construction & registration hook speedups:
_registration_hookbypassesKeyErrorexceptions using direct dictionary lookups on watched storage,construct()calls constructors directly on CPU withouttorch.device("cpu")overhead whentorch_function_stackis empty, and_build()hoistswith registry.activated():outside node loops. - Pretrained caching & loader consolidation:
@lru_cache(maxsize=256)bounds_file_digests,_load_safetensors_stateunifies safetensors checkpoint extraction across Hugging Face and timm providers, andLocalProvidercaches pre-resolved submodule targets. - Fused RMSNorm and AdaptiveNorm kernels:
RMSNorm.forwardleverages native PyTorch C++/CUDAF.rms_normwith full float64 precision preservation, andAdaptiveNorm.forwardcombinesF.instance_normwithtorch.addcmulaffine fusion, while un-fused mathematical formulations are retained in_reference(module)for reference validation. - Cached RoPE tables & causal mask simplification:
Attentioncaches 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 exponentiationROPE_BASE ** (-exponent), and constructs causal attention bias viatorch.full((T, T), float("-inf")).triu(1). - Mixture of Experts sparse dispatch and 0-graph-break compilation:
MixtureOfExperts.forwardevaluates active routed tokens via sparsetorch.whereand in-placeindex_add_in eager mode, and transitions to branchless dense scatter and unrolled accumulation during TorchDynamo tracing whentorch.compiler.is_compiling()is true, achieving 0 graph breaks undertorch.compile(..., fullgraph=True). - Separable 1D ragged adaptive average pooling:
AdaptiveAvgPool2d.forwardevaluates ragged 2D pooling via separable 1D window aggregation (_pool_axisalong 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:
EqualLinearprecomputesself._scaleduring initialization;Hopfieldhoists transposed weight matrix access and prestores normalized shapes;FeedForwardbinds activation functions directly without lambda wrappers;PoolTokensbinds the reduction callable at construction time;SpatialAttentionandTransformerBlockfuse residual scaling and additions withtorch.addcmul. - Operator relation deduplication: Extracted reusable
non_imageandreduce_axisrelations, reusedconv_axisandconv_outputacross pooling and resblocks, deduplicatedeval_weightacross equalized operators, and streamlinedsplitandgroup_normrelations. - Per-sweep constraint solver convergence:
_Solver.runvalidates 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:
_Solverpre-allocates node views and port references once during initialization, andOperator.__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_nodesusesheapqand integer in-degrees to sort nodes deterministically with optimal asymptotic complexity. - Redundant validation skip in
build():ResolvedPlantracks a validated stamp(id(registry), limits)set duringresolve_graphorvalidate_concrete_plan, allowingbuild()to skip redundant validation passes when the plan is unchanged. - Plan digest caching & default settings singletons:
ResolvedPlan.semantic_digestis 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.pyfast-paths ASCII line locations and integrates AST depth tracking directly into the validator pass. - Compiler code readability and decomposition: Decomposed
Capture.emitinto_bind_inputsand_rethrow_with_source, decomposed_ordered_nodesinto 4 cohesive functions, unified plan table rendering (format_plan_table) and shape formatting (format_shape), and isolatedconv_axisargument unpacking. - Benchmark input generation consolidation: Unified
random_inputshelper intests/_network_examples.pysupporting 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.pyto prevent JIT and cache compilation skew from contaminating timing runs, removed deadDEVICEconstants, and tagged all benchmark metrics with explicit[{device}]labels for clear CPU/CUDA differentiation. - Testing infrastructure documentation: Authored
TEST_INFRA.mdformalizing the 4-tier testing hierarchy and mapping all 38 features fromPROJECT.md, and certified test readiness inTEST_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.inincludesCHANGELOG.md,src/hndl/py.typed, and recursive test JSON fixtures (recursive-include tests *.py *.json), ensuring runningpytestagainst an unpackedsdistfinds all 0.6.0 plan compatibility fixtures. - Specification and implementation catalog synchronization (
H-08): SynchronizedIMPLEMENTATION.mdandSPEC.mdto document the 69 built-in operators across 12 categories, documented random initializers undertorch_default@2, documentedArg.sinceinSPEC.md, and added synchronization tests intests/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 indocs/pretrained.md. - Operator documentation and benchmark comment hygiene (
L-09): Addedscriptsdirectory to theruff checkchecklist indocs/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): Configurednorecursedirs = [".*", "build", "dist", ".claude", ".agents"]under[tool.pytest.ini_options]inpyproject.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 namesp=ref:[...]), aligning plan printing withGraphModule.__repr__.make_operatorandOperator.__post_init__strictly enforce that operators declaringpositional_resthave nopositional=Truearguments, andOperator.positional_namesreturns an empty tuple()whenpositional_restis set. - Public API typing and PEP 561 compliance (
M-11): Addedsrc/hndl/py.typedmarker package, enabledfrom __future__ import annotationsacross core modules, replaced untyped: objectsignatures intypes.pyandoperator.pywith 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_TEMPin.github/workflows/publish.ymland added a dedicated sdist unpack and test step; addeddevelopbranch toon.push.branchesin.github/workflows/ci.yml; wireddevicefixture across benchmark tests and alignedHandwrittenTransformerBlockintest_parity_vs_handwritten_pytorch.pyto use 3 separateLinearprojections andF.scaled_dot_product_attentionmatchingAttention; intercepted production URLs inscripts/gen_doc_pages.pyto map to internal Markdown targets. - RMSNorm double-precision preservation (
H-06):RMSNorm.forwardpreservesfloat64precision when running double-precision inputs instead of downcasting tofloat32, ensuring exact parity againstF.rms_normand passingtorch.autograd.gradcheck. - RoPE double-precision calculations (
M-12):attention._rope_tablescalculates frequency exponents, inverse frequencies, and angles infloat64whendtype=torch.float64, preventing numerical noise and precision degradation during double-precision attention evaluation. - PosEmbed sequence length bounds validation (
M-12):PosEmbed.forwardvalidates that input sequence length does not exceedmax_len, raisingHNDLError("E_CONSTRAINT")instead of silently broadcasting position 0 across longer sequences. - Dense Mixture of Experts reference oracle (
M-12):MixtureOfExperts._referenceprovides 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 exactreference=implementations, achieving 100% reference coverage across all 68 non-pretrained builtin operators. - Dedicated operator test modules (
M-13): Added 15 comprehensive unit test suites intests/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 deadself.sizeattribute and unused*, input_shapesparameter fromChunk.__init__, allowing direct instantiation without requiring dummy shape dictionaries. - GridSample positional argument alignment (
L-07): Optional argumentsmode,padding_mode, andalign_cornersingrid_sampleare configured withpositional=Falseand provided with default parameter values inGridSample.__init__. - Spatial operator and linear layer representations (
L-08): Added comprehensiveextra_repr()implementations toCoordinateGrid,FourierFeatures,GridSample,EqualLinear, andAttention(reportingequalized={self.equalized}). - ResBlock channel divisibility validation (
L-08):ResBlock.__init__validates thatout_channels % groups == 0whennorm="group_norm"raisingHNDLError("E_CONSTRAINT"), and supports direct construction with arbitrary extra kwargs. -
TransformerBlock reference deduplication (
L-08):transformer_block._referencededuplicates attention, normalization, and feed-forward math by delegating directly to the submodule reference implementations ofAttention,FeedForward,LayerNorm, andRMSNorm. -
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 unhandledIndexErrorin 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 withE_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 withE_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): Falsyinput_dtypevalues ("",False,0,()) are preserved and rejected withE_SCHEMArather than silently coerced tofloat32. - 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 acrossGraphdefinitions,Capture, andresolve_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_shapeandNode.args/inputs/outputsvalidate 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_AMBIGUOUSreports 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.axisand_Solver.intervalbounds-check axes to guard against negative axis aliasing andIndexError;conv_input_rangereturns empty interval(1, 0)on non-positive extents;conv_transpose_inputreturnsNonewhen mathematically unreachable;conv_axisverifies valid axes and guards againstNonecontext. - Chain classification and slice step validation (
H-03):_is_chainnow verifiestuple(node.outputs) == ("out",)so single-output tuple-returning operators (chunk(1)) are not misclassified as unary chains, andGraphModule.__getitem__strictly rejects non-unit slice steps (step != 1) withValueError. - Pre-forward state verification on compile path (
M-08):GraphModule._executenow verifies registered state matches the build before executing forward whentorch.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._applynow clearsself._validatedin place, ensuring that casting a shallow copy invalidates cached signatures on the original graph, and_record_stores/_executetracks parameter/buffer dtypes and devices to prevent unhandled ATen errors upon submodule in-place casts. - Pretrained trainable mode synchronization (
H-04):GraphModule._buildnow callssubmodule.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.instantiateforwardsself.source.revisionasf"{model_name}@{revision}"for Hugging Face Hub (hf://) sources, andTimmProvider.__init__accepts defaultcomponent=""and falls back gracefully toarchitectureinsource.config. - Pretrained checkpoint cache invalidation and weight hashing (
M-01):resolve_sourceseparates 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.safetensorsand 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-8config.jsonfiles and unreadable weight files are caught and raised as structuredHNDLError("E_PRETRAINED")rather than rawJSONDecodeError,UnicodeDecodeError, orOSError;TimmProvider.instantiateverifiessafetensorsavailability before loading checkpoint weights. - Meta-device view storage deduplication (
L-06):_state_bytesnow keys meta-device storages by(value.device, storage._cdata)rather thanid(value), accurately deduplicating storage footprints for parameter and buffer views onmetadevices.
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.
opscalls custom operators. Insideresolve_callableornetwork_from_callable, the globalfrom hndl import opsnow looks each alias up in the registry that capture runs under, so an operator registered on it is called asops.my_op()instead of failing withE_OPERATOR.registry.ops.my_op()still works and mixes freely withopsin one capture. Outside a captureopsstill 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. Callingother.ops.my_op()in a capture whose registry does not hold that exact declaration used to fail withE_STATE_VERSION; it now fails withE_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 anyRegistry.builtins()keep working in every built-in registry, which shares their declarations. The message suggestsops.<alias>only when the capture's registry binds that alias to the same identity, and otherwise names the operator the alias binds there. hndl.relationsis public. The convolution arithmetic, the 2D convolution relation, elementwise joins and broadcasting that the built-ins use inrelation=functions move from the privatehndl.operators._relationsto a documented module, joined byconv_input_range,conv_transpose_inputand the per-axis relationsconv_axisandconv_transpose_axisfor operators with their own strided axes. The old import path re-exports them. The per-axis relations fail withE_CONSTRAINTwhen a port's rank has no such axis.hndl.testingis 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_runandcheck_referencerun one check each, andexample_paramsandoperator_paramsbuild pytest parameters for them. The built-in suite now runs through it. Importinghndlorhndl.testingdoes not import pytest. A check fails withAssertionError, except where HNDL itself rejects the example while resolving, building or running it, such asE_RUNTIMEfor a module whose output shape differs from its declaration.devicesanddtypestake one name or a list, and the class must carry its own docstring rather than inherit one.docs/ADDING_OPERATORS.mdcovers operators declared outside the package: calling them throughops, reusinghndl.relationsin a strided operator's relation, testing them withhndl.testing, and adding arguments withArg(since=...).- Registered-state edits PyTorch runs no hook for are caught on the next
call.
del module.weight,linear.bias = Noneand direct writes to a module's_parameters,_buffersor_modulesused 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 areNone, 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 toNoneor added, or a submodule replaced, fails the next call with the sameE_RUNTIMEreport as a registration, naming the node and what changed. A tensor swapped in under a registered name is not a change, sotorch.func.functional_callstays on the unchecked path, and the record holds no tensors, so nothing a functional call passed in is kept alive or reachescopy.deepcopy. Not detected: a whole mapping replaced, a mapping reordered, one name removed and another added in the same_parametersor_buffersbetween 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):.Nis a positive integer literal, loops nest, and the body takes any top-level statement, soh = add(h, feed_forward(layer_norm(h), 512))in a loop stacks residual blocks. A loop builds exactly the nodes, plan, semantic digest andstate_dict()keys of the statements written out by hand.name="block"inside a loop becomesblock0,block1, ...; nested loops append every index, outermost first (res1_3). There is no loop variable, arithmetic or conditional: other targets,rangeforms,while,break,continue,if, comprehensions and_as a value fail withE_SYNTAX, and index-dependent structure belongs in native Python. A loop that would unroll pastmax_nodes, or loops nested more than 8 deep, fail withE_RESOURCEbefore any node is created. Configuration, resolution and runtime errors about an unrolled node report the iteration, as inline 12, column 5, iteration 3 of 8, from newiterationsnode source metadata.rangeis 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 -Sworker, 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. Beforeast.parseruns, 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 crashast.parseon a small thread stack instead of raising; such input now fails withE_SYNTAXorE_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_INTEGRITYfrom revalidation lists every differing port shape and argument per node. A plan missing only an operator default (saved before the operator gained that argument, likepretrainedplans from beforelayers=) 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_bytesrises 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_jsondrops its 16 MiB input cap and duplicatemax_nodescheck; revalidation still appliesmax_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_RUNTIMEnames 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 spelledfloat32, nottorch.float32. An exception raised inside a layer keeps its type, message and traceback (aRuntimeErroror out-of-memory error is still caught as one) and gains a note, viaadd_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 ---delof 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, andgrid_samplefor style-conditioned coordinate renderers composed in HNDL. Fourier tables and coordinate grids are persistent buffers; sampling follows PyTorch semantics. -
Add opt-in
equalized=Truetolinear,attention, andfeed_forward: raw N(0,1) weights, zero biases, and runtime1/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.
Argacceptssince="<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.equalizedis declared this way, so plans saved by 0.6.0 load again (they failed withE_INTEGRITY), and any plan that does not setequalized=Trueencodes and digests byte for byte as in 0.6.0. Writingequalized=Falseexplicitly 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-parameterinitmapping 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(orfrom hndl.initializers import ...) gives plain functions returning the record the declarative parser builds, soops.linear(init={"weight": xavier_uniform(gain=1.0)})andlinear(init={"weight": xavier_uniform(gain=1.0)})resolve to the samesemantic_digest. The eight names are reserved: registering an operator alias that shadows one isE_REGISTRY, and a parse request carrying one isE_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 bareinit=xavier_uniform(), a scheme in a list, a scheme nested inside another scheme's arguments, a scheme intrainable={...}or in any other keyword's dictionary, and any non-initializer call inside a literal container all remainE_SYNTAX, rejected by the isolated AST validator before any operator lookup happens. -
Plan format:
initialization.kindgainstorch_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 eachE_INITIALIZATION. -
attentionlearns a 2D relative-position bias. Withattention(4, spatial_shape=(16, 16), relative_position_bias=True)the[B, T, D]sequence is read as a row-majorH x Wtoken grid --- tokentsits atrow = t // W,col = t % W--- and each head learns one bias per query-minus-key offset, the Swin/ViT/TransGAN construction. The learned parameter isrelative_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 additiveattn_mask, soscaled_dot_product_attentionstill picks a fused kernel; withcausal=Trueas well, the causal-infmask and the bias are summed into one additive mask rather than handed to the kernel separately. The table is constructed at0.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-persistentint64buffer rebuilt fromspatial_shape, so it stays out of checkpoints.H*Wmust equalT: a grid that does not cover the sequence isE_CONSTRAINTat resolution rather than a silent broadcast, andrelative_position_bias=Truewithout a positivespatial_shape--- or aspatial_shapewithoutrelative_position_bias=True--- isE_ARGUMENT. The operator carries no windowing of its own: partition a map into windows withchunk, reassemble it withconcat, and give the node the(H, W)of one window. -
attentiongains per-projection bias flags.qkv_biasandout_biasnarrow the existingbiasflag:q_proj,k_projandv_projcarry a bias whenbias and qkv_bias, ando_projwhenbias and out_bias. Both default toTrue, sobias=on its own behaves exactly as it did --- one flag for all four projections --- whileattention(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 nobiasparameter at all, so itsstate_dictis unchanged frombias=False. -
Plan format:
attentionnodes carry four more arguments.qkv_bias,out_bias,relative_position_biasandspatial_shapeare concrete on every resolvedattentionnode, so a plan saved by 0.5.0 that contains anattentionnode no longer matches its own digest and must be re-resolved from its configuration; the configuration itself is unchanged. Plans without anattentionnode encode and digest exactly as they did. -
Faster forward passes.
GraphModuleno 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 andModuleDictlookups per call. The fixed per-node overhead drops from about 13 us to about 5 us on the reference machine: intests/benchmark/test_parity_vs_handwritten_pytorch.pythe 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, andtransformer_blockfrom ~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 sameE_RUNTIMEmessages. -
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
_modulesmapping 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.Noneslots and tensors already seen earlier in the walk are filtered exactly asnamed_parametersandnamed_buffersfilter them. Detection is therefore unchanged from 0.5.0 — including a forward that fills a declared-Noneparameter, buffer or submodule slot (the lazy-initialization bug, wherebuild()hands the caller an emptyparameters()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 withself.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.
-
concatjoins along the batch axis, tracked ask*B.axis=0was rejected; it now stacks examples, socombined = 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, throughpretrained(includinglayers=), in the saved plan, and in the runtime shape check, which requiresktimes the batch of the call. The sum runs both ways, so2*B + Bis3*Band one unknown input batch is solved from a known total. Externalinput_shapeandoutput_shapecontracts stay one plan batch (E_SCHEMA), so a graph chunks a joined tensor back before publishing it. -
New
chunkoperator: one axis into equal sections.a, b = chunk(x, 2)halves a feature axis anda, b = chunk(features, 2, dim=0)takes a2*Btensor back apart into twoBtensors, the inverse of the join above. It produces exactlychunksoutputs (1 <= chunks <= 32), returns a tuple and clears the current tensor likesplit, and its sections are views, so first and second derivatives reach the input through every one of them. Uneven divisions fail at resolution withE_CONSTRAINTrather than at a runtime that would only ever see one batch size: an extent of 5 into 2 sections, a2*Bbatch into 3, and a plainBbatch into 2 are all rejected when the plan is resolved.chunks=1is allowed and returns a one-tuple, matchingpretrained(..., 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 withE_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"for2 <= k <= 1024; external contracts may not. -
outputs_from=accepts anintargument. A variadic output port could only take its count from the length of a sequence argument; it now also accepts a boundedintargument, which is whatchunk'schunksis. Operators declare how they treat axis 0 withbatch="shared"(the default: batch passes through every port) orbatch="relation", and a relation can read and set batch entries withs.batch(port)ands.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 annn.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 assplitdoes, including for a one-entrylayers=("layer1",); an emptylayers=()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 withlayer=orreadout=each fail withE_PRETRAINED. Because plan digests cover every canonical argument, a plan saved before this release that holds apretrainednode fails to restore withE_INTEGRITYand must be re-resolved once from its source; plans without apretrainednode are unaffected. - Operators may declare variadic output ports. A shape declaration can
write
out*after the arrow together withoutputs_from="<argument>", and the node expands ordinal portsout0,out1, ... from that sequence argument's length, mirroring thex0,x1expansion of variadic inputs. An empty sequence leaves the single declaredoutport, so such an operator's existing plans keep their encoding and digests.Argalso gains a"strs"type: a bounded tuple of strings, written as a tuple literal in configuration. .hndlfiles count as Python on GitHub. A.gitattributesat the repository root maps*.hndlto 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 withcopy.deepcopycarry the dtype the original was cast to, and casting a copy leaves the original alone. - Named readouts for provider checkpoints. A
.pthcheckpoint whose useful tensor comes from a method rather thanforward— DINOv2'sforward_features(x)["x_norm_patchtokens"]orget_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 namedcallable(model, x)readouts to a provider (andregistry.pretrained_readout(provider, name, fn)adds one later), which a network selects withpretrained("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=andlayer=are mutually exclusive, an unknown name lists the readouts the provider offers, and neither applies to transformers or timm checkpoints, which selectoutput=.
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 eachrequires_gradflag 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 atplan.to_json()plustorch.save(model.state_dict())instead of failing inside the pickler.broadcast_addoperator. 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 withsum, so it is deterministic on CUDA.addkeeps its exact-shape contract.adaptive_avg_poolis deterministic and double-differentiable. When the input extents divide the output size it pools by reshaping and taking ameanover the window axes, and a ragged pool to at most 64 windows writes the windows out with slicing andstack. Both paths run undertorch.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 toF.adaptive_avg_pool2d, whose CUDA backward is nondeterministic. Values, shapes, arguments, and the modulereprare unchanged.- Spectral normalization.
linear,conv,conv1d, anddeconvacceptspectral_norm=True, wrapping the weight withtorch.nn.utils.parametrizations.spectral_normfor GAN discriminators. The learned tensor is then registered asparametrizations.weight.original, which is the nameinitandtrainableoverrides must target. - Local
.pthcheckpoints with custom providers.pretrained("weights.pth", provider="vgg16", sha256="<hex>", layer="features.16")loads a plainstate_dictinto an architecture the host registered withregistry.pretrained_provider(name, build). Registration is trusted Python on oneRegistryinstance; 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 withtorch.load(..., weights_only=True)andstrict=True, andlayer=returns an intermediate submodule's output through a forward hook that stops the pass there — what perceptual losses and feature matching need. constantoperator. Emits a[B, *shape]tensor filled withvalue(default0.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.matmuloperator. 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 dimensionKflows in both directions; other ranks are rejected withE_CONSTRAINT, so reshape a[B, C, H, W]map to[B, C, H*W]first.learned_scaleoperator.out = gamma * xwith one learned scalar parameter namedgamma, started frominit_value(default0.0, the SAGAN convention that makes a gated residual begin as the identity). Usescalefor a fixed constant.- SAGAN self-attention example.
examples/networks/sagan_attention.hndlbuilds the Self-Attention GAN block (Zhang et al. 2018) from registered operators alone: 1x1 projections,reshape/transpose, twomatmuls around asoftmax, and alearned_scalegate on the residual. - Named external inputs and outputs.
input_shapeandoutput_shapeaccept a mapping of named contracts —{"z": ("B", 128), "y": ("B", 10)}— in everyresolve*/network*entry point, andinput_dtypeaccepts 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. Thenetwork*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.hndltakes an image and a label and publisheslogitsandfeatures.
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 hndland 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
masterbydocs.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.Modulewith 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 aRegistry. Documentation is generated from the declarations withpython -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, anddropout. Convolutions gain thedown2policy, mirroringup2. - Sequences and dtypes. Rank-3
[B, T, D]tensors, plan dtypesfloat32,float16, andbfloat16, integer input ports (input_dtype="int64"), and edge dtype checking. pretrained(source). Loads any checkpoint thattransformersortimmcan build from its configuration, from a local directory, a safetensors file, orhf://repo[@revision], as one frozen node whose output shape comes from a meta-device trace. Optional extrahndl[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 intodocs/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-nodestate_bytes/state_versionplan fields from the 0.1.0a1 alpha.