Skip to content

Changelog

All notable changes to Lucid. Keep a Changelog format.

Adds Drifting Models (arXiv 2602.04770), checked against the authors' running release: generator, MAE and ConvNeXt features, the drift loss and its gradient agree to float32 noise. Fixes a run of lucid.compile steps that trained on silently wrong gradients or losses: in-place writes on tensors the call made, no_grad regions inside a forward, dropout under a segmented step, batch-norm statistics, compiled contiguous, and traced Functions inside a traced backward. lucid.set_grad_enabled is a context manager and decorator, lucid-audit --models verifies the zoo on both Metal and CPU, and the engine ABI is 46.

Added

  • lucid.peft / lucid.quantization: add QLoRA support — QuantizedMatmulBackward in _C.engine propagating dX gradients (including create_graph=True and float16/bfloat16/float32 activations) through quantized_matmul on Metal, lora.QuantizedLinear adapting QuantizedLinearMLX, nn.quantized.Linear, and nn.quantized.dynamic.Linear with lossless unmerge() buffer restoration and "all-linear" discovery, and prepare_model_for_kbit_training support for quantized models (LCD-717).
  • lucid / Tensor / linalg / signal.windows: add asarray, scalar_tensor, layout, strided, deg2rad, rad2deg, logaddexp2, sgn, fix, diag, diagflat, concatenate, split_with_sizes, unsafe_chunk, unsafe_split, constant_pad_nd, unravel_index, select_scatter, slice_scatter, diagonal_scatter, dist, gradient, linalg.cholesky_inverse, linalg.lu_unpack, Tensor.{mH,is_cpu,is_meta,layout,ndimension,nelement,sum_to_size,fill_diagonal_,polygamma,t_,transpose_,swapaxes_,swapdims_,squeeze_,unsqueeze_,exponential_,cauchy_,geometric_,log_normal_,random_}, and layout=/requires_grad= keyword arguments on all 12 signal.windows functions (LCD-685).
  • lucid.peft: SwinConverter, CLIPConverter, and DETRConverter adapter-file converters supporting both release-4 and release-5 reference module layouts, fusing separate query/key/value (q_proj/k_proj/v_proj) and out_proj (o_proj) projections into the zoo's qkv nn.Linear and nn.MultiheadAttention modules (LCD-830).
  • add post-accumulate hooks, node hooks/next_functions, and C++ saved_tensors_hooks
  • select lucid-audit packages, the model zoo included
  • verify the model zoo on Metal, as an option and on record
  • add the rule registry and its audit
  • let the quality gate judge from a ref (LCD-841-R2)
  • judge a push to main, record a bypass (LCD-841-R2)
  • add Drifting Models (arXiv 2602.04770)
  • export FCNOutput and EfficientFormerOutput
  • validate_model_zoo rejects unexported public names (MZ080)
  • judge the ABI bump and attest the C++ at push (LCD-841-R3)
  • verify the model zoo on Metal and CPU by design

Fixed

  • lucid.compile: make_step(segments=N) froze a value one segment stores and a later one reads (a dict, list, attribute or closure stash) and trained on the first call's value with a wrong gradient; it now runs eagerly with a segment-values notice and equals eager (LCD-902).
  • lucid.compile: a compiled function using masked_select, linalg.lu_factor_ex, linalg.ldl_factor_ex or linalg.householder_product returned the first call's result for every later input with no error. These signatures now run eagerly and answer each input (LCD-836).
  • linalg.pinv raises LinAlgError on an infinite matrix with min(m, n) >= 3 instead of never returning, and linalg.lstsq returns a NaN solution for a non-finite batch element, as the reference does, instead of raising (LCD-833).
  • ErrorBuilder / LapackInfo / Indexing: prefix C++ errors with the public operation name (take, index_select, transpose, unfold, scatter, frombuffer, clamp, fft, tril/triu, linalg.*), omit [trace=...] unless LUCID_ERROR_TRACE is set, format index-out-of-bounds messages with the offending index, dimension, and extent, report human-readable LAPACK convergence/factorization failures, and raise ValueError instead of RuntimeError on invalid scalar/shape arguments across 19 ops (LCD-673, LCD-675).
  • linalg.eigh, linalg.svd, and linalg.pinv: raise LinAlgError on non-finite inputs across CPU and Metal when min(m, n) >= 3 (svd/pinv) or when any referenced triangle entry is non-finite (eigh), and report the failing batch index on batched eigh (LCD-674).
  • compile / coreml: clamp bitwise shift counts (bitwise_left_shift, bitwise_right_shift) in MPSGraph to $[0, W-1]$ (masking shifts of W or more to 0 on unsigned and <<, and to W - 1 on arithmetic signed >>), support signed integer pow (int8/int16/int32/int64) in MPSGraph with negative-exponent error parity, and cast int64 pow operands to int32 in Core ML MIL export (LCD-727).
  • metal: wrap_mlx_array binds thread streams and evaluates in place when an op outside the dispatcher (fft, qr, eigh, scatter_add) is a thread's first MLX work; synchronize_gpu and ready_buffers release the GIL only while waiting on a stream token after encoding (run_then_wait), closing cross-thread command-buffer deadlock windows (LCD-701).
  • _C.engine: validate TensorImplPtr arguments at C++ entry points (cummax, cummin, ravel, sum, prod, square, cube, concatenate, concat, stack, meshgrid, einops.einsum) so passing None raises TypeError instead of dereferencing a null pointer (LCD-683).
  • random_uniform: clamp floating-point uniform draws to nextafter(hi, -inf) in the target dtype precision (float16, bfloat16, float32, float64, complex64) on both CPU and Metal so the half-open interval $[lo, hi)$ never rounds up to hi (LCD-774).
  • matmul (mm, bmm) and dot: reject bool operands with NotImplementedError on CPU and Metal rather than promoting to integer accumulation (LCD-775).
  • pad: add int8, int16, and bool kernels with saturating constant-fill conversion on CPU and Metal, and remove the int8/int16 promotion workaround in pooling windows (LCD-791).
  • cummax and cummin: support float16 and bfloat16 backward passes (create_graph=False and create_graph=True) on CPU and Metal (LCD-682).
  • max_pool{1,2,3}d and adaptive_max_pool{1,2,3}d: return zero gradient (instead of routing gradient to index 0) on all--inf windows, pick the first NaN window index on CPU and Metal, and map constant-padded window positions to valid input indices when return_indices=True (LCD-748).
  • lucid.tensor(..., dtype=bfloat16, device="metal"): convert float64 host sequences to bfloat16 bits on CPU before uploading raw uint16 words to Metal so bfloat16 subnormals are preserved on M4 Max (LCD-746).
  • count_nonzero, logical_not, logical_and, logical_or, logical_xor, cdist(..., p=0), and linalg.vector_norm(..., ord=0): route truthiness tests through _truth_mask (astype(Bool) / complex real-or-imag mask) so subnormal floating-point values on Metal are preserved as nonzero rather than flushed to zero by not_equal(..., 0) (LCD-745).
  • nn: MultiheadAttention exposes an out_proj nn.Linear view over out_proj_weight/out_proj_bias and merge_masks(attn_mask, key_padding_mask, query), TransformerEncoderLayer and TransformerDecoderLayer name their FFN/residual dropout modules dropout/dropout1/dropout2(/dropout3), TransformerEncoder exposes use_nested_tensor, and LPPool2d exposes kernel_size and stride attributes (LCD-753).
  • compile / quantization: fused_step carries outside in-place buffer writes (including QAT FakeQuantize observers) back via run_executable_inplace instead of falling back to eager; QuantizedLinearMLX preserves input floating dtype (float16/bfloat16), moves CPU-resident packed buffers onto Metal on demand, and warns when called with a requires_grad=True input; compiled_step supports models with unused parameters and raises clear errors on non-scalar or detached losses (LCD-724).
  • arange / as_strided / conv{1,2,3}d / unfold / fold: _exact_int64_arange checks the range element count before unpacking into struct.pack, as_strided_positions refuses output sizes above INT32_MAX, and ConvNd / Unfold / Fold compute output spatial dimensions in int64_t before checking bounds so oversized padding or shapes raise RuntimeError/ValueError cleanly (LCD-700).
  • lucid.float_power promotes complex operands to complex128 instead of dropping the imaginary part into float64, and lucid.expm1 / lucid.sinc avoid ordering comparisons (clamp) on complex inputs so higher-order derivatives (create_graph=True) work on complex tensors (LCD-698).
  • compile_optimizer: CompiledOptimizer.state (and the wrapped optimizer's .state) is now a live read-only view over the compiled state buffers keyed by Parameter, matching state_dict()["state"] and eager Optimizer.state (LCD-813).
  • lucid.diffeq.odeint and odeint_dense: support complex initial states y0 (complex64 / complex128) across fixed-step and adaptive Runge–Kutta solvers (rk4, dopri5), and lucid.finfo now accepts complex dtypes and returns the underlying real component limits (LCD-817).
  • lucid.nn: F.one_hot rejects non-integer index tensors, F.batch_norm(..., training=False) requires running_mean and running_var to be defined, F.conv{1,2,3}d / F.conv_transpose{1,2,3}d reject weights with zero channel dimensions, and ReflectionPad{1,2,3}d, ReplicationPad{1,2,3}d, and CircularPad{1,2,3}d enforce batched or unbatched spatial input ranks (LCD-699).
  • record trace I/O for masked_select, LU, LDL, householder
  • name unsafe_split's first parameter input (LCD-844)
  • measure short zoo stages, type the stage for mypy --strict
  • erase the zoo's live frame, say what a narrowed floor held
  • lead a killed stage's failure with who killed it
  • stop baselines and zoo records saying more than was checked
  • keep nohup's hangup ignore, find a family's tests by class
  • take the weights axis's probe out of the registry
  • follow a write into the views that share its buffer
  • compile: a view taken before an in-place write to its base no longer keeps the value from before the write. A compiled call that reads such a view, as an op input, as a value copied into another tensor or as its return value, now runs eagerly and matches eager. Core ML export of a function returning such a view raises ValueError instead of exporting the pre-write value. Views of batch norm running statistics and overlapping buffers written in one call also follow eager.
  • build tables for the default device (LCD-849)
  • create_model under lucid.set_default_device("metal") gives a model whole on Metal. I-JEPA, V-JEPA and Stable Diffusion no longer raise on float64 at build, and Transformer, NCSN, DiT and learned-variance DDPM no longer leave a table on the CPU.
  • make the rule audit prove what it claims
  • run eigh on the Jacobi graph svd already uses (LCD-838)
  • replay MPSGraph's clone walk before compiling (LCD-838)
  • lucid.compile no longer hangs on eigvalsh and eigh of 4x4 and larger, or on full-matrices svd. eigh shares the one-sided Jacobi graph with svd and pinv, and returns up to the 16x16 limit.
  • Compiled graphs with deep equal-arm diamonds (x = x * a + x * b in a loop) no longer stall in MPSGraph's clone walk.
  • Compiled svd, svdvals, pinv, cond and matrix_rank no longer return wrong values for inputs with entries around 1e-7 or smaller.
  • A compiled eigh or svd call on NaN or inf input returns all NaN for that batch member, V included, and leaves the other members untouched.
  • keep shadow calls out of interpolate's matrix cache (LCD-858)
  • compute a Metal result's shape before dispatch (LCD-850)
  • answer phantom gradients without reading storage (LCD-850)
  • keep embedding_bag's dtype refusal in its graph backward
  • refuse what Metal cannot hold as a phantom too (LCD-850)
  • answer a phantom index as an integer (LCD-850)
  • shadow_alloc on Metal no longer raises bad_variant_access from where, inner and tensordot, or from the ops built on them such as clamp, lgamma, cross_entropy and Embedding(padding_idx=...).
  • Under shadow_alloc, kthvalue on the CPU, the gradients of cummax, cummin and det, second gradients of embedding_bag and bilinear resampling, device moves, the Metal quantized ops, and create_graph=True through sort, msort, kthvalue, quantile and nanquantile answer with phantoms.
  • create_graph=True through embedding_bag works on Metal.
  • post-commit's CHANGELOG amend no longer folds other staged files into a path-limited commit.
  • keep svd's U orthonormal, eigh finite at the limit
  • Compiled linalg.svd returns an orthonormal U (and Vh on wide input) for rank-deficient and zero matrices, where it left zero or non-orthogonal columns.
  • Compiled linalg.pinv with a small rtol keeps a column under 1e-12 of the largest entry; diag(1, -1e-13) came back 13 orders short.
  • Compiled linalg.eigh and eigvalsh no longer return inf or NaN on entries past 1.7e38, and they read back an eigenvalue beside one up to 38 orders larger when the eigenvectors don't mix them.
  • cast after the move when .to() goes to the CPU (LCD-866)
  • trace a non-materializing VJP once per demand (LCD-863)
  • leave out a demand variant backward cannot trace
  • match the demand for a lone region missing a cotangent
  • refuse a non-materializing call no subset traces for
  • refuse a call whose full variant misses an input gradient
  • Compiled training steps through svd, svdvals, matrix_norm(nuc), eigh and eigvalsh on a repeated or zero spectrum (identity or orthogonal weights) no longer give NaN gradients. A custom Function that does not materialize grads now gets, in a compiled step, the cotangents eager gives it for the outputs a gradient reached (None for the rest).
  • split a max/min gradient among ties and keep NaN
  • decide a write by the buffer it lands in
  • compare a shared buffer's writer by view family
  • close the holes the write-landing review found
  • write a fused step's output into a shared buffer
  • leave a held table written from constants alone
  • give a held tensor back what the eager rerun did not write
  • let the trace stand as the call when its rerun would read empty
  • hold no result tensor past the answer handoff
  • let a fused step's trace stand as the call too
  • put back only a held tensor the call reads as it writes
  • count a write noted twice once, and step a standing call's counters
  • rerun a step whose cumulative batch norm traced without buffers
  • stand for any held write where the trace can stand
  • leave a compiled step's held writes to its call
  • hold the zoo build budget to a measured count (LCD-851)
  • give self pairs their exact distance
  • prove the C++ push checks' run lines, refuse a run of skips
  • prove what the attest key reads, drop autoload-off
  • keep regions off a recorded backward's inner calls
  • contiguous aliases in a trace as it does eager (LCD-890)
  • dropout with nothing to drop is its input in a trace (LCD-890)
  • carry a functional batch norm's statistics from lucid.compile
  • let a segment's trace stand for a tensor it keeps
  • refuse a write a compiled run cannot carry
  • support unary plus, refuse it on a boolean tensor
  • keep or refuse a rectangular sample_size, never square it
  • Drifting promises no weights, saves only its generator
  • a later ABI: none no longer excuses an earlier move
  • check_weight_fit claims OK only for what it read
  • an in-place op's stand-in reads the value it stands for
  • an overwrite in a recording keeps its zero derivative
  • a tensor put back also leaves the trace's graph
  • a held tensor put back leaves the trace's graph
  • what a write moves besides its values, under a trace
  • a value made under no_grad is a constant to the backward
  • make set_grad_enabled a scope and a decorator
  • replay a segment's draws in its backward recompute
  • a checkpoint reading the grad mode runs eagerly

Performance

  • _C.engine (Linear, ConvNd, ConvTransposeNd, LayerNorm, RMSNorm, BatchNormNd, GroupNorm, BatchNormEval, GlobalResponseNorm, Bilinear): thread needs_input_grad (grad_mask) and kGradReads through fused CPU/Metal backward kernels and apply_for_graph, skipping unneeded dx/dW/db GEMMs, convolutions, reductions, and buffer allocations (LCD-697).
  • CpuBackend::roll, lucid.fft, and lucid.signal.windows.kaiser: replace the per-element modulo and single-element memcpy loop in CpuBackend::roll with a row-wise two-slice std::memcpy rotation (cutting (256, 4096) CPU roll/fftshift from 5.1 ms to 0.049 ms), dispatch CPU power-of-two single-precision FFTs (fftn/ifftn/rfftn/irfftn) directly through Apple Accelerate vDSP with thread-local plan/scratch caching and GCD parallelization across slices (cutting 64-point CPU fft from ~100 µs to 5.6 µs and (256, 4096) CPU fft/ifft from 2.8 ms to 0.41 ms), and use Horner evaluation and scalar denominator evaluation in lucid.i0 / windows.kaiser (cutting kaiser(64) from 420 µs to 99 µs) (LCD-769).
  • lucid.special.log_ndtr: replace log1p on the upper-tail erfcx correction (|q| <= 2.34e-3) with a short Horner Mercator series, cutting Metal first-compile time from 4.4 s to 1.6 s while preserving full float32 / float64 accuracy (LCD-795).

Tooling

  • lucid-audit: --subsystem now narrows the test-suite and doctest stages and per-file coverage checks to the selected subsystems (LCD-733).

Changed

  • tools/convert_weights/: the one-off weight conversion scripts are removed; only __init__.py remains, and earlier converters stay in git at e1858082c. The YOLO parity check reads its darknet releases from tools/_darknet_release.py, and tools/check_tvm_upstream_parity.py carries its own key map. TVM weights are not being converted.
  • merge float/double vDSP plans into one template
  • give fused-backward grad masks one owner (LCD-834)
  • stop depending on one-off weight converters
  • let the zoo stage define its own command-line options
  • lucid-audit is scoped by package (--<package>, --no-<package>, children included) and the model zoo is a package (--models, included by default, --no-models leaves it out). The zoo runs family by family on Metal by default (--zoo-device cpu to change), under a memory budget taken from the machine. Baselines are written only by a run that covers everything, and only --tests-only can fail the line coverage floor. --subsystem and --list-subsystems are removed (use --list-packages), --no-metal is now --cpu-only, and lucid-audit --models replaces tools/verify_zoo.py.
  • F.sinusoidal_embedding, F.sinusoidal_embedding_2d, make_beta_schedule, make_sigma_schedule, diffusion_posterior_constants, flow_prior_sample, sample_point_coords and DDPMScheduler default device to None, the current default device, instead of "cpu". Behaviour under a CPU default is unchanged.
  • shadow_alloc refuses float64 and complex128 on Metal with the NotImplementedError a real allocation raises.
  • A push to main or a v* tag is now judged again by .githooks/pre-push (python -m tools.rules push), and a commit that skipped pre-commit carries a Lucid-Bypass trailer and a log line.
  • The pre-commit hook runs the rule registry's commit level on the staged blobs, so a git add -p of part of a file under lucid/ is refused. LUCID_SKIP_H4_GUARD and LUCID_SKIP_QUALITY_GATE are gone: --no-verify is the only way past those checks, and it leaves the trailer.
  • The DreamerV3 learning benchmark (TestDreamerV3ReadsTheGoal) scores every policy on a fixed 36-goal panel, treats the goal-blind ceiling as a policy, and asserts what the goal is worth to the policy (the cost of a decoy), over 3000 steps. The old test's blind ceiling was not a ceiling, and its verdict was one random draw.
  • A compiled step through a _traced_backward Function with _materialize_grads=False (or ctx.set_materialize_grads(False)) traces its backward once per set of outputs a gradient may reach; one that cannot be traced for the demands it may meet runs eagerly, and the fallback warning says why. More than 4 differentiable outputs run eagerly.
  • bring the family under the gate
  • make the encoder and queue private
  • prefix family-internal helpers with an underscore
  • give Drifting's feature encoder its own module
  • Drifting says guidance_scale like the zoo (LCD-891)
  • drop the no_grad guards nothing reaches
  • drop an assert the typed no_grad makes redundant
  • _pow2 picks its path from the engine's grad mode ---