Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

DragonScale

Left: a pre-norm transformer, whose residual stream and weight pairs can trade scale freely; middle: nGPT and EDM2, which fix every scale by construction; right: DragonScale, unit rows with a gain only where the loss sees the scale. Right panels: hidden-state size against learning rate for a small language model, standard and patched, and the number of free scales against how fast the hidden state grows with the learning rate

A moving scale is a scale that training can change, because a trainable tensor carries it: the length of a raw weight row, a gain, a norm's weight. A unit row without a gain has a fixed scale: nothing moves it.

A free scale is a moving scale that the loss does not see: rescaling it leaves the output unchanged, either at every size or once it is large. In a transformer MLP you can multiply up by 2 and divide down by 2 and get the same output. The loss gives no gradient along such a direction, but every optimizer step still moves the weights a little along it, and those moves add up. The residual stream of a pre-norm transformer is the largest case: it can grow while the output layer shrinks to match.

DragonScale finds the free scales of a PyTorch model by tracing one forward pass. It then gives every weight unit rows, a fixed scale, and puts a moving scale back only where the loss sees it. After the patch, no free scale that the weights can reach changes a hidden state; the report names what is left for the model code.

Contents: Highlights · Install · Quick start · How it works · Why scales drift · What DragonScale changes · Results on small models · Kernels and speed · Training notes · Supported layers and limits · Checkpoints · Repository

Highlights

  • Finds every free scale in one forward pass and names the tensors in each one, split into those that change a hidden state and those that do not.
  • Leaves no free scale that changes a hidden state at every size. The tests check this on small versions of a language model, a diffusion transformer, a ViT student and a ConvNeXt student, and that what remains is held only by a fixed-scale term the report names.
  • Keeps the hidden state in place. On a small language model with Adam, the standard model's hidden state grows about 2,500x for every 10x in learning rate; the patched model's grows 1.1x.
  • Hand-written Triton kernels by default. On an NVIDIA B300 the unit-row op is 1.3x to 12x faster than its torch.compile version (GPU time, 8 weight shapes, 3 dtypes). With torch.compile of the whole model, a patched layer's training step is 0 to 23% slower than the plain layer's.
  • fp16 AMP and bf16 AMP. Row lengths are summed in fp32, and every backend matches an fp64 reference to the rounding of the weight's own dtype.

Install

pip install "dragonscale[triton]"    # GPU, with the Triton kernels
pip install dragonscale              # CPU only

From source: pip install -e ".[triton]". Needs Python 3.11+ and PyTorch 2.9+.

Quick start

import torch
from torch import nn

import dragonscale as ds

torch.manual_seed(0)
model = nn.Sequential(  # a small pre-norm transformer: embedding, one block, output layer
    nn.Embedding(256, 64),
    nn.TransformerEncoderLayer(64, nhead=4, dropout=0.0, batch_first=True, norm_first=True),
    nn.Linear(64, 256),
)
tokens = torch.randint(0, 256, (8, 33))
x, y = tokens[:, :-1], tokens[:, 1:]

# Which scales can move without the loss seeing them?
print(ds.analysis.free_scales(model, x).describe())

# Unit rows everywhere, a gain only where the loss sees the scale.
session = ds.patch_model(model, x)

# Gains are ordinary parameters; weight decay goes on the raw weights only.
optimizer = torch.optim.AdamW(ds.optim.param_groups(session, weight_decay=0.1), lr=1e-3)
for step in range(10):
    loss = nn.functional.cross_entropy(model(x).flatten(0, 1), y.flatten())
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

session.bake()  # back to stock modules with the trained weights, same output

The report for this model, in part:

4 free scale(s): 4 change a hidden state, 0 change none; 0 of them held only by a fixed-scale term; 0 op call(s) without a rule
  +1 0.weight +1 1.self_attn.out_proj.weight +1 1.self_attn.out_proj.bias +1 1.linear2.weight +1 1.linear2.bias -1 2.weight
  +1 1.linear1.weight -1 1.norm2.weight -1 1.norm2.bias

Each line is one free scale: scale each tensor on it by c to the power shown, and the output stays the same. The first line is the residual stream. The embedding and both layers that write into the stream grow together, and the output layer shrinks to match. The second is a norm's affine trading scale with the layer that reads it. A line marked * would be held only by a fixed-scale term: there the output changes, but less and less as the scale grows. docs/analysis.md explains the rest of the report, and docs/patching.md the steps inside ds.patch_model, for when you want to edit the plan.

How it works

flowchart LR
    model["your model"] --> report["ds.analysis.free_scales(model, x)<br/>the free scales, by tensor,<br/>and what the model code could change"]
    model --> patch["ds.patch_model(model, x)"]
    subgraph patch_steps [" "]
        patch --> plan["suggest: move norm affines and pair scales,<br/>keep a gain only where the loss sees it"]
        plan --> apply["apply: unit rows times a gain"]
    end
    apply --> train["train as usual<br/>any optimizer"]
    train --> out["session.bake()<br/>stock modules"]
    train --> native["session.canonicalize()<br/>ds.nn modules"]

A patch can only change weights. Some free scales come from the model code itself, for example a norm in front of the output layer. The report names those, and fixing them is up to you (see the model-side rules).

Why scales drift

Give every parameter tensor $\theta_i$ a log-scale $s_i$. A free scale is a way to rescale whole tensors, a vector $s$, whose effect on the output is zero, or goes to zero as the scale grows. There are two kinds, and both count as free.

Exact: the output is unchanged at every scale,

f(\theta_1 e^{t s_1}, \dots, \theta_n e^{t s_n}) = f(\theta_1, \dots, \theta_n) \quad \text{for every } t .

Examples: up $\times c$ with down $\times 1/c$; q $\times c$ with k $\times 1/c$; a norm's gain $\times c$ with every layer that reads it $\times 1/c$.

Held only by a fixed-scale term: the output changes only because a term of fixed scale (a fixed-scale input, a constant, a buffer) is added to the scaled one. Scale the layers that write to the residual stream by $c$ and the stream becomes $h = e + cB$, with $e$ the fixed-scale input. After a norm, the output changes by about $|e| / |cB|$: the ratio fixed / scaled, which falls like $1/c$ as the stream grows. The gradient along that scale falls the same way while the optimizer's step does not, so the scale drifts like an exact one.

The loss is constant along an exact free scale, so its gradient has no component there. For a weight $w$ whose scale is free on its own, $\langle \nabla_w L, w\rangle = 0$, and one gradient step $w' = w - \eta g$ gives

\lVert w' \rVert^2 = \lVert w \rVert^2 + \eta^2 \lVert g \rVert^2 \ \ge\ \lVert w \rVert^2 .

The norm can only grow. With Adam every entry moves by about $\eta$ per step whatever its gradient, so a row of $n$ entries drifts like a random walk, about $\sqrt{n}$ times faster than a single gain. Weight decay pulls the other way. The norm then settles where the two balance, at a size set by the learning rate and the decay, not by the loss.

What DragonScale changes

A patched layer computes with unit rows in place of its weight:

W_{\text{eff}} = \mathrm{diag}(g)\; r\; \frac{W}{\lVert W \rVert_{\text{row}}}

The length of a row no longer matters; only its direction and its gain do. The gain is one way to put a moving scale back where the loss sees it; another is to leave that layer an ordinary weight without unit rows, whose row length is then the moving scale (ds.Rule(..., mode="plain"), or the plain role of suggest). Here $r$ is a fixed row length: 1 for linears and convs, $\sqrt{\text{dim}}$ for embeddings. The raw row length no longer reaches the output, so its drift does nothing. The scale lives in the gain $g$, one number per row, which the loss does see. Without weight decay the raw rows still grow slowly, and each step turns them a little less: under Adam the turn per step falls as $1/\sqrt{t}$ (figure C below).

Where the gains go is the one choice left:

patch_model(..., gains=) gain on free scales left that change a hidden state output at the start
"all" (same as level="absorb") every patched layer the stream, through the gains unchanged
"selective" (default) only where the loss sees the scale none from the weights changes in the layers that lose their gain
"none" the output layer only, with output_gain none changes in every layer

With the default, the embedding, the output layer, and q and k behind a QK-norm lose their gain. Their rows restart at length $r$, so the output at the start changes. In the quick start it changes by up to 1.9, against an output RMS of 0.61, and ds.apply logs the two layers. That is fine for training from scratch. For a pretrained model, use level="absorb", which keeps the output unchanged, or plan to re-train. With output_gain, the output layer keeps a gain that trades with the stream's scale: one free scale remains, held only by the fixed-scale input.

Biases keep their own scale. A bias added to a fixed-scale term (a unit-row layer without a gain, a norm's output) is held only by that term, and the report lists it with the notes; weight decay on biases, or no bias, keeps it in place.

Model-side rules

The patch removes every free scale it can reach through weights. The rest needs changes in the model code, and the report's notes say which apply:

  • norms without an affine, or with the affine moved into the next layer (absorb_plan does this);
  • every input enters at a fixed scale: an embedding with unit rows, or a norm after a patch embedding;
  • the output layer reads the residual stream directly; a norm in front of it leaves one free scale: the scale of the residual stream, held only by the fixed-scale input;
  • q and k normalized, with a gain on one side only (ds.nn.QKNorm);
  • LayerScale folded into the gain before it (ds.fold_layerscale).

Limitation: scale means the scale of a whole vector

Everywhere in this library a scale is one positive number per tensor: the length of a weight row, of a hidden-state vector, of the residual stream. A free scale rescales whole tensors, and that is what the analysis finds and the patch removes.

How the magnitude is spread over the channels of one vector is outside its view. A hidden state can have a moderate overall size and still hold a few channels with extreme values, and a patched model can have them too. These outlier (or massive) channels are a separate problem with its own literature:

The patch also leaves alone any scale the loss does see: such a scale can still grow when the loss asks for it.

Results on small models

All figures: a small transformer language model (2 blocks, width 64, byte vocabulary), Adam, 3,000 steps. Lines are medians over seeds; bands run from the lowest to the highest seed. Data and scripts: docs/figures.

Hidden-state RMS against learning rate, standard and patched

A. 5 seeds. The standard model's hidden state grows by about 2,500x per 10x learning rate. The patched model's stays between 2 and 3.6 up to learning rate 3.2. Crosses: every fp16 AMP run of the standard model went non-finite there.

Free scales counted by the analysis against hidden-state growth per 10x learning rate, the standard model, DragonScale with the output norm kept, and DragonScale

B. 5 seeds. The standard model has 12 free scales that change a hidden state, and its hidden state grows about 2,500x per 10x learning rate. Keeping the norm in front of the output layer leaves 1 free scale, and the hidden state grows 7.8x. DragonScale has none and grows 1.1x.

Angle a unit row turns per step times sqrt(t), against step

C. 5 seeds, patched model, AdamW without weight decay. Once its steps are large enough, a unit row turns by sqrt((1 - β1) / (1 + β1)) / sqrt(t) per step, whatever the learning rate and the initial scale.

Cosine-output model: hidden-state RMS and held-out loss against learning rate

D. 5 seeds, with a cosine (scale-invariant) output. Here a gain the loss cannot see is itself a free scale: with gains the hidden state still grows, without them it does not, at the same loss.

Held-out loss against learning rate in fp32 and fp16 AMP

E. 5 seeds, fp32 and fp16 AMP. From learning rate 0.03, every fp16 AMP run of the standard model goes non-finite. The patched model's fp16 AMP runs follow its fp32 runs.

Hidden-state RMS on three data sources, and growth per 10x learning rate for eight widths and depths

F. Left: three Markov data sources of different entropy, 5 seeds. Right: eight widths and depths, 3 seeds. The standard model's hidden state grows by 550x to 3,300x per 10x learning rate, the patched model's by 1.1x to 1.2x.

Kernels and speed

The unit-row op reads a weight and writes one of the same size, so its speed is set by memory bandwidth. On CUDA it runs on hand-written Triton kernels. Without Triton it falls back to the torch.compile version of the op, then to plain torch, and logs one line naming the backend at first use. ds.apply(..., backend=...) pins one. Under torch.compile of the whole model the op is traced as plain torch ops and fused with the rest.

Effective bandwidth of the unit-row op, forward and backward, per backend, on three large weights in fp32, bf16 and fp16

On large weights the Triton kernels move 5.3 to 6.9 TB/s on an NVIDIA B300, about the same as the op fused inside a compiled model, and 1.4x to 3.3x the torch.compile backend's rate.

Training-step time of a patched layer as a share of the plain layer's, per backend, bf16 AMP

A whole training step of one layer, bf16 AMP. A large matmul hides most of the op: with the kernels the step is 2% slower for 768->3072 and 6% slower for 4096->11008. Small, fast layers do not hide it. In eager mode a 3x3 conv step is 57% slower, and a stack of 72 small linears 83% slower, or 34% with the grouped launch, which computes every weight of the model in one launch (group=True, the default). With torch.compile of the model, the step is 0 to 23% slower.

The eager cost is on the host, not the GPU. Each patched layer adds two kernel launches and one autograd node whose backward runs in Python: about 0.2 ms per layer per step on this machine. This release cut each launch from about 36 µs to 26 µs; the rest is PyTorch's autograd. The grouped launch pays the cost once per model, and torch.compile removes it.

The kernels are as accurate as plain torch. Row lengths are summed in fp32 for every weight dtype, so under fp16 AMP and bf16 AMP the norm is computed in fp32. Worst error against an fp64 reference, over the output and both gradients of seven weight shapes, relative to each row's largest entry:

weight dtype Triton kernels torch.compile plain torch (fp32 sums) plain torch at the weight's dtype
fp32 (the master weights under AMP) 2.6e-7 2.7e-7 2.5e-7 2.4e-7
bf16 3.9e-3 3.9e-3 3.9e-3 1.3e-2
fp16 4.9e-4 4.9e-4 4.9e-4 1.7e-3

Backends, benchmark scripts and where the per-shape numbers are: docs/kernels.md.

Training notes

  • Weight decay. ds.optim.param_groups(session, weight_decay) decays the raw weights of patched layers and other matrices, and leaves gains, biases and norm affines alone. Decay on a raw weight does not change the output. It shrinks the raw rows, so later steps turn them further.
  • Warmup. The first steps turn a unit row the most (figure C). A short learning-rate warmup limits them.
  • fp16 AMP and bf16 AMP. Keep the master weights in fp32 as usual. fp16 AMP needs its gradient scaler, as for any model.
  • EMA and eval. In eval mode every forward recomputes the unit rows, so an EMA update or a load_state_dict shows up at once. Inside with session.cache_weights(): they are computed once; call session.invalidate() after changing weights there.
  • Rows that never update. An embedding row whose token never appears keeps its first value. Row lengths are floored at 1e-12, so a zero row stays zero and finite on every backend.

Supported layers and limits

  • Patched: Linear, Conv1d/2d/3d, ConvTranspose1d/2d/3d, Embedding, MultiheadAttention, the layers inside TransformerEncoderLayer, and transformers' Conv1D. ds.layer_types.register_layer_type adds more. Tied weights share one gain.
  • Tested with torch.compile, DistributedDataParallel, FSDP2 (fully_shard), copy.deepcopy and torch.save of the whole model.
  • The analysis traces one forward pass, so control flow that depends on the data is seen only as it ran on the example input. An op without a rule is reported, never guessed, and suggest stops unless you pass allow_unknown=True.

Checkpoints

call result
session.state_dict("raw") raw weights and gains
session.state_dict("baked") the unit-row weights under the stock keys; loads into the stock model
session.bake() stock modules with the unit-row weights, same output
session.canonicalize() the patched modules become ds.nn modules
session.remove() the patch undone; the weights keep what training wrote

Patch options, presets, the ds.nn modules and the monitor: docs/patching.md.

Repository

path contents
src/dragonscale/ the library: analysis, plans, patching, kernels, ds.nn modules
tests/ the test suite, including the README and docs code blocks
measure/ops/ speed, precision and overhead benchmarks of the unit-row op
docs/ analysis and patching notes, kernel tables, figures and their data

Citation

To be added.

Licence

Apache-2.0.

Metadata

Release files for dragonscale 0.2.2.dev20261125115329

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for dragonscale 0.2.2.dev20261125115329
File Size Uploaded Provenance Actions
dragonscale-0.2.2.dev20261125115329.tar.gz 97.4 kB With provenance Details for dragonscale-0.2.2.dev20261125115329.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for dragonscale 0.2.2.dev20261125115329
File Interpreter ABI Platform Actions
dragonscale-0.2.2.dev20261125115329-py3-none-any.whl Python 3 none any Details for dragonscale-0.2.2.dev20261125115329-py3-none-any.whl

Total release size: 188.1 kB

Release files / dragonscale-0.2.2.dev20261125115329.tar.gz

Download URL dragonscale-0.2.2.dev20261125115329.tar.gz
Size 97.4 kB
Tags Source
SHA-256 checksum
How to use checksums
92802c68c1159c9f80bea742b19c4ab962fac494cb2f8582464013828534f61f
BLAKE2b-256 checksum
How to use checksums
55bfc9fa62dd017ed2de500341236166fe3eac90fc3727e2c121a5c9ee43a58e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.

Transparency log

Release files / dragonscale-0.2.2.dev20261125115329-py3-none-any.whl

Download URL dragonscale-0.2.2.dev20261125115329-py3-none-any.whl
Size 90.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9c62c1c7c959262c352cb9919359d64f19a6b06125316f27e0622a5e1951625d
BLAKE2b-256 checksum
How to use checksums
ce222697eaea5bdb37fc4018b674051b225172e06b91e99ff7140f05623935c5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.

Transparency log

Security for dragonscale 0.2.2.dev20261125115329

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for dragonscale-0.2.2.dev20261125115329.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page