Model Carving: Training Transformers That Optimize Their Own Topology
Abstract: Machine learning has largely kept separate the choice of architecture and the process of training. A classic Transformer, for instance, trains a fixed set of attention and MLP sublayers at every layer, in the same order, and optimizes the weights within. This uniformity is a convention rather than a principled design choice, and it is likely suboptimal: the best architecture for a given task may be smaller, more efficient, and far from uniform. We believe that, ideally, training itself should shape the model's topology. To this end, we introduce Model Carving, which learns both a Transformer's weights and its architecture in a single run. By applying learnable, scalar gates to each sublayer, we allow the training loss to remove the model's own components during training -- freeing a smaller heterogeneous network inside. We evaluate Model Carving by pre-training standard Transformers from 140M to 2.7B parameters and looped Transformers from 140M to 1.3B. At equal training compute, carved models reach a lower validation loss than dense models trained with up to 1.7 times more compute. Furthermore, carved models also outperform size-matched models produced by pruning or distillation, suggesting that the best way to obtain small models for edge devices is to carve them during training, not to compress a large one afterwards. This advantage both grows with scale and carries over to downstream tasks such as few-shot evaluation and generation. Because the removed sublayers no longer run, carved models also cost up to 34% fewer FLOPs per token and decode up to 1.6 times faster without cost in quality. Our results show that architecture, like weights, should be learned and not fixed in advance, and that inside every large transformer is a smaller, faster, stronger one waiting to be carved out.
Paper Prompts
Sign up for free to create and run prompts on this paper.
Explain it Like I'm 14
1. What is the paper about?
This paper introduces a method called Model Carving. It teaches a Transformer LLM to improve not only its internal numbers, called weights, but also its shape and structure, called its architecture.
Normally, researchers decide a model’s structure before training begins. For example, they choose how many layers it has and where the attention and MLP parts go. Model Carving starts with a large model and lets the model remove parts it does not need while it is training.
A simple way to imagine this is like growing a tree:
- The model first grows many branches.
- During training, it checks which branches are useful.
- Weak or unnecessary branches are cut away.
- The final tree is smaller, faster, and still very strong.
2. What questions are the researchers asking?
The researchers mainly want to know:
- Can a model learn its own architecture while it learns a task?
- Can removing unnecessary parts make a model faster without making it worse?
- Is learning the structure during training better than shrinking a model afterward?
- Can this method find different structures for different tasks?
- Does Model Carving become more useful as models get larger?
The central idea is that a model should keep a part only when that part improves its performance enough to justify the computer power needed to run it.
3. How did the researchers do it?
Starting with an oversized model
The researchers began with large Transformer models. They tested:
- Standard Transformers from 140 million to 2.7 billion parameters
- “Looped” Transformers from 140 million to 1.3 billion parameters
A parameter is a number learned during training. More parameters usually allow a model to learn more, but they also make the model slower and more expensive.
The models were trained to predict the next word or token in text from the FineWeb-Edu dataset.
Adding gates
Each important part of the Transformer was given a learnable gate. The gate works like a dimmer switch:
- A large gate means the part is being used strongly.
- A small gate means the part is being used less.
- A gate of zero means the part is completely turned off.
The researchers placed gates on the model’s attention and MLP sublayers.
- Attention helps the model decide which earlier words are important.
- An MLP, or multilayer perceptron, transforms information inside the model.
Comparing usefulness with cost
The model continuously compared two things:
- How much a sublayer helped reduce mistakes
- How much computer power that sublayer used
If a sublayer used a lot of computing power but helped very little, the model lowered its gate. Eventually, the sublayer was removed from the model’s computation.
This is similar to deciding whether a tool is worth carrying in a backpack. If a tool is heavy but almost never useful, you leave it behind.
Using saved computing power
When the model removed a sublayer, training became cheaper. The researchers used the saved computing power to train on more text.
This made the comparison fair: the carved model and the ordinary model received about the same total training-computing budget.
Comparing with other methods
The researchers compared Model Carving with:
- A normal full-sized Transformer
- A smaller Transformer designed from the beginning
- Pruning, which removes parts after a model has already been trained
- Distillation, where a smaller student model learns from a larger teacher model
They measured:
- Validation loss, which shows how well the model predicts text
- Performance on 22 other tasks
- Speed during text generation
- The number of computer operations, called FLOPs
- Performance on special tasks such as arithmetic and symbolic reasoning
4. What did they find?
The carved models were smaller but often better
Model Carving removed many sublayers while maintaining or improving quality. In standard Transformers, the final models had about 66% to 86% of the original number of parameters.
They also used 8% to 34% fewer operations per token during use.
Despite being smaller, the carved models generally had:
- Lower validation loss
- Better or equal scores on other tasks
- Better performance than ordinary smaller models
The results were especially strong for looped Transformers.
They were faster
Because removed sublayers no longer ran, carved models generated text faster.
The paper reports that carved models could decode text:
- Up to 1.45 times faster at the same batch size
- Up to 1.61 times faster at each model’s largest tested batch
They also needed less memory for the information they store about previous tokens.
Carving worked better than pruning and distillation
The carved models performed better than models created by:
- Removing parts from a finished model
- Shrinking the width of a model
- Teaching a smaller model to copy a larger model
This suggests that deciding what to remove during training may be better than waiting until training is finished.
The advantage increased with model size
The researchers found that Model Carving became more helpful as the models and training budgets became larger.
For example, one carved looped model reached the same quality as a normal model that would have needed up to about 1.7 times as much training computation.
This means the usual design of repeating the same kinds of layers throughout a Transformer may become increasingly inefficient for large models.
Different tasks kept different parts
The researchers also tested simple mathematical and symbolic tasks.
For modular addition, the model removed almost everything and kept only two attention sublayers out of 24. It still reached 99% accuracy.
This is important because it shows that the method can discover that a task does not need every kind of computation. Some tasks may need attention, while others may need MLPs or deeper processing.
5. Why is this important?
Most LLMs are built with a fixed structure. Researchers choose the number and order of layers first, then train the model’s weights. This paper argues that the model’s structure should also be learned.
The possible benefits include:
- Faster AI systems: Smaller models can respond more quickly.
- Lower costs: They require less computing power.
- Better use on phones and small devices: Devices with limited memory could run stronger models.
- Less energy use: Running fewer calculations can reduce electricity consumption.
- More flexible models: Different tasks could produce different useful architectures.
- Improved large models: The method may become even more valuable as models grow.
Conclusion
The paper’s main message is that a large Transformer may contain a smaller, more efficient model inside it. Model Carving discovers that smaller model during training by giving each part a gate and removing parts that are not worth their computational cost.
The experiments suggest that models trained this way can be smaller, faster, and sometimes more accurate than ordinary models or models compressed afterward. In the future, this approach could help create powerful AI systems that are cheaper to train and easier to run on everyday devices.
Practical Applications
Immediate Applications
The paper’s results support several applications that can be implemented now using existing Transformer training and deployment infrastructure, although most require adapting and validating the method for a specific workload.
- Lower-cost deployment of LLMs at the edge (software, mobile computing, IoT)
- offline assistants;
- on-device summarization and translation;
- document search;
- predictive text;
- voice interfaces;
- industrial or field-service copilots.
- Dependencies: hardware-specific benchmarking is necessary; the reported results were obtained primarily on language modeling workloads and selected GPUs. Quantization, compiler support, tokenizer overhead, and memory bandwidth may determine whether the FLOP savings translate into equivalent real-world gains.
- More efficient cloud inference and LLM serving (cloud software, data centers) Use carved models as drop-in replacements for dense models with similar quality. Lower compute per token can reduce serving costs, increase requests per GPU, and permit larger batches. The smaller key-value cache reported in the paper may also improve long-context serving and multi-tenant utilization. Potential tools/workflows: a training-time carving stage in an LLM development pipeline, followed by topology export, kernel compilation, quantization, and deployment through systems such as standard Transformer inference servers. Dependencies: production gains depend on whether the serving stack can compile and optimize heterogeneous layer patterns; dynamic graph overhead should be avoided by exporting the final static graph.
- Cost-efficient high-sample generation and search (reasoning systems, coding assistants, mathematics)
- best-of- answer selection;
- code candidate generation;
- mathematical solution sampling;
- retrieval-query expansion;
- synthetic data generation.
- Dependencies: additional samples are useful only when a reliable verifier, reranker, or selection mechanism exists. The gains may be smaller for tasks where diversity rather than raw sample count is the limiting factor.
- Training-time architecture optimization for new LLMs (AI industry and academic research) Replace a fixed “train large, prune later” workflow with a single run that jointly learns weights, gates, and connections. This can be integrated into pretraining pipelines to produce a task- and budget-specific heterogeneous Transformer. The paper reports that carving outperforms several pruning and distillation baselines at matched training compute. Dependencies: the initial overparameterized model must contain the operations that the final model may need. The method also requires reliable learning-curve extrapolation, graph recompilation, and a predefined training FLOP budget.
- Task-specific student models without a separate teacher-training stage (education technology, enterprise NLP, developer tools)
- compact enterprise document assistants;
- domain-specific search models;
- classroom tutoring models that run on school hardware;
- local code-completion models.
- Dependencies: the paper evaluates language modeling and several downstream benchmarks, but deployment should include domain-specific validation, safety testing, and regression tests after carving and quantization.
- Compute-aware model selection for public-sector and organizational procurement (policy, sustainability, infrastructure planning)
- training FLOPs;
- inference FLOPs per token;
- latency at realistic batch sizes;
- memory and KV-cache requirements;
- quality under equal-compute comparisons.
- Dependencies: reported costs must use consistent measurement conventions. Training energy, hardware utilization, data preparation, and repeated experimental runs can offset some savings.
- Research tool for discovering task-relevant computational circuits (academia, mechanistic interpretability)
The learned gates and connections can be inspected to identify which attention and MLP sublayers are necessary for a task. The symbolic experiments suggest a workflow for:
- training an overcomplete model;
- observing which components survive;
- testing the reduced circuit independently;
- comparing circuits across random seeds, tasks, and scales. Dependencies: a surviving sublayer is not necessarily a human-interpretable “concept,” and different seeds may produce different but functionally equivalent topologies. Causal ablations are needed before drawing scientific conclusions.
Curriculum and benchmark analysis through learned topology (education and evaluation research) Researchers can compare the architectures carved by different datasets, curricula, or objectives. For example, a LLM trained on arithmetic, code, or legal text may retain different sublayer profiles. This can reveal whether a benchmark requires genuinely different computation or merely different parameter values. Dependencies: topology can be affected by initialization, pressure schedules, optimization settings, and the chosen compute budget, so comparisons require controlled experiments.
- More efficient local privacy-preserving AI (healthcare, finance, personal computing) Carved models can support local processing of sensitive text without sending data to a cloud service—for example, clinical note assistance, personal financial categorization, or private email summarization. Reduced computation may make local inference more practical. Dependencies: efficiency does not establish safety, privacy, or accuracy. Healthcare and financial applications require domain validation, auditability, security controls, and compliance with applicable regulations.
Long-Term Applications
These applications are plausible extensions of the paper’s findings but require additional research, broader validation, or substantial engineering before dependable deployment.
- Automatic architecture discovery for multimodal and domain-specific foundation models (vision, speech, healthcare, robotics)
- local versus global attention;
- cross-modal fusion blocks;
- convolutional stages;
- memory modules;
- state-space layers;
- modality-specific expert pathways.
- Dependencies: the current evidence focuses mainly on Transformer LLMs and looped variants. New operations require accurate compute accounting, stable gates, and objectives that reflect communication and memory costs as well as FLOPs.
- Hardware-aware neural architecture optimization (chips, robotics, edge AI)
- mobile NPUs;
- automotive processors;
- warehouse robots;
- drones;
- wearable devices;
- custom inference ASICs.
- Dependencies: FLOPs are only a proxy for actual cost. Heterogeneous topologies may be efficient mathematically but poorly supported by current kernels. Hardware-in-the-loop training or accurate differentiable cost models may be required.
- Adaptive architectures for robotics and embodied systems (robotics, autonomous vehicles) Carving could identify compact perception, planning, or control networks for robots with strict power and latency constraints. A robot could be trained with an overcomplete policy network and retain only the computation needed for a particular environment or task. Dependencies: robotic workloads are distribution-shifted and safety-critical. A topology that is efficient on training environments may fail under rare conditions. Robustness testing, formal safety constraints, continual-learning safeguards, and real-world trials would be essential.
- Energy-aware AI training and inference (energy and sustainability) By reducing both final inference cost and, in some cases, the effective cost of reaching a target loss, carving could contribute to lower energy consumption and carbon emissions. A future implementation could optimize directly for energy or carbon intensity rather than FLOPs, choosing different architectures depending on the datacenter, time of day, or available hardware. Dependencies: total environmental benefit must include the overhead of training the overparameterized gated model, repeated experiments, graph compilation, and hardware utilization. Energy measurements—not FLOP estimates alone—are needed.
- Continual and personalized model specialization (personal assistants, enterprise software) A general model might be adapted to an organization, user, or device by carving task-irrelevant components during continued pretraining or fine-tuning. This could yield specialized models for legal research, scientific literature, customer support, or personal workflows without retaining the full general-purpose architecture. Dependencies: carving may remove capabilities that are not represented in the adaptation data. Techniques for preserving general knowledge, preventing catastrophic forgetting, and validating rare capabilities would be required.
- Dynamic or conditional topology at inference time (adaptive computation, real-time systems) The paper removes sublayers permanently during training. A future extension could learn several valid topologies and select among them based on input difficulty, confidence, or latency constraints. Easy inputs might use a highly carved path, while difficult inputs activate additional components. Dependencies: this introduces routing overhead, possible worst-case latency, and more complicated verification. It would also need to demonstrate advantages over early exiting, mixture-of-experts routing, and conventional conditional computation.
- Architecture-aware scaling laws and compute allocation (AI research and policy planning)
- parameter count;
- number and type of active sublayers;
- training tokens;
- inference cost;
- expected downstream quality.
- Such laws could guide national laboratories, companies, and universities in selecting models that maximize capability under fixed energy or budget constraints.
- Dependencies: the current scaling evidence covers a limited range of model sizes, datasets, and architectures. Larger models, longer contexts, multilingual data, and instruction-tuned or reinforcement-trained systems may exhibit different behavior.
- Certified compression for regulated applications (healthcare, finance, public administration) A carved model could potentially be paired with formal or statistical guarantees showing that removing a component does not materially reduce performance on specified subgroups or safety-critical cases. This would support compact models for clinical decision support, fraud detection, or public-service triage. Dependencies: the paper reports aggregate benchmark improvements, not fairness, calibration, robustness, or subgroup guarantees. Certification would require sensitive-data evaluation, reproducibility, monitoring, and domain-specific regulatory approval.
- Topology libraries and reusable architecture templates (software engineering and model platforms) Since the paper reports high transferability of some standard-Transformer removal patterns across scales, future platforms could maintain libraries of prevalidated topology templates for different model families, hardware targets, and workloads. Training could begin from a topology prior and use carving for final adaptation. Dependencies: transferability was weaker for looped Transformers and may not hold across datasets, tokenizers, modalities, or training objectives. Templates should therefore be treated as initialization heuristics rather than guaranteed optimal architectures.
- Automated model lifecycle management (MLOps and enterprise infrastructure)
- budget specification;
- gated training;
- topology export;
- hardware compilation;
- quality and safety evaluation;
- versioned deployment and rollback.
- Dependencies: changing topology complicates model versioning, reproducibility, monitoring, and compliance. Reliable rollback and regression detection are necessary before using this workflow in critical systems.
Glossary
- Adaptive computation: A model-design approach in which the amount or path of computation depends on the input. “One field that has emerged to pursue this has been adaptive computation”
- Adam: An adaptive gradient-based optimization algorithm that maintains estimates of first and second moments of gradients. “we subtract from that the penalty gradient , divided by Adam's denominator”
- AdamW: A variant of Adam that decouples weight decay from the gradient update. “We use Muon \citep{jordan2024muon} for the weight matrices and AdamW”
- Attention sublayer: A Transformer component that computes token interactions using attention mechanisms. “Fundamentally, a Transformer layer applies an attention sublayer and then an MLP sublayer”
- AUC: Area under the receiver-operating-characteristic curve, a measure of how well a scoring system distinguishes between two classes. “The AUC measures how well these predictions separate removed from kept sublayers”
- Bias-corrected moments: Adjusted estimates of gradient statistics that compensate for initialization bias in adaptive optimizers. “with and the bias-corrected first and second moments”
- Block Influence (BI): A pruning metric measuring how substantially a neural-network layer changes its input. “defines a layer's Block Influence (BI) as how much the layer changes its input”
- Bootstrap interval: An uncertainty interval estimated by repeatedly resampling observed data. “with paired 95\% bootstrap intervals over prompts”
- Compute-optimal: Describing a model size or configuration that achieves the best performance for a fixed computational budget. “we calculate the compute-optimal point for carved models versus standard models”
- Computation graph: A structured representation of operations and dependencies used to execute and differentiate a model. “the trainer removes those sublayers from the computation graph”
- Distillation: Training a smaller student model to reproduce the outputs or behavior of a larger teacher model. “the dominant paradigm of building these is to start from a larger model that is pruned and retrained or used as a teacher for model distillation”
- e-fold: A unit corresponding to multiplying a quantity by Euler’s number, , approximately 2.72. “we measure progress in e-folds of tokens”
- Evolutionary loop: An iterative architecture-search process that generates and evaluates candidate models using evolutionary operations. “or an evolutionary loop”
- Finite-difference estimate: An approximation of a derivative calculated from differences between discrete measurements. “ is a finite-difference estimate of the rate ”
- Forward KL divergence: A directional measure of discrepancy between a teacher probability distribution and a student distribution, used here for distillation. “We train this student on the forward KL divergence to the teacher's next-token distribution”
- FLOP: A floating-point arithmetic operation, commonly used as a unit for measuring computational cost. “Given a specified training FLOPs budget”
- GELU: The Gaussian Error Linear Unit, a smooth neural-network activation function. “with learned LayerNorm, GELU MLPs, and rotary position encoding”
- Gradient: A vector of derivatives indicating how a loss changes with respect to model parameters. “the gradient measures at every update”
- Hard-concrete mask: A differentiable stochastic gate used to approximate discrete binary selection, such as retaining or removing a layer. “learns hard-concrete masks on whole attention and MLP sublayers”
- Heterogeneous architecture: A model architecture containing varied rather than uniformly repeated components. “freeing a smaller heterogeneous network inside”
- IsoFLOP: A comparison between models using the same number of floating-point operations. “Model Carving produces models with lower loss than standard models when compared both at isoFLOP and isoToken”
- IsoToken: A comparison between models trained on the same number of tokens. “when compared both at isoFLOP and isoToken”
- Key-value cache: Stored attention keys and values reused during autoregressive decoding to avoid recomputing previous tokens. “The removed attention sublayers also shrink the key-value cache”
- Lagrange multiplier: A parameter representing the marginal value or cost of satisfying a constrained optimization budget. “This value of one FLOP is the Lagrange multiplier of the budget”
- LayerNorm: Layer normalization, which normalizes neural-network activations across features within a layer. “with learned LayerNorm”
- Learning-curve extrapolation: Estimating future training behavior by extending an observed relationship between training progress and performance. “which Model Carving does by extrapolating the run's own learning curve”
- Logarithmic penalty: A penalty based on the logarithm of a parameter, used here to approximate a discrete cost while retaining differentiability. “we replace each count by the logarithmic penalty”
- Mixture-of-Experts: A neural architecture that routes inputs to a selected subset of specialized expert networks. “Mixture-of-Experts \citep{shazeer2017outrageously}”
- Muon: An optimization algorithm used in the paper for updating weight matrices. “We use Muon \citep{jordan2024muon} for the weight matrices”
- Neural architecture search (NAS): Automated optimization of a neural-network architecture, usually separate from ordinary weight training. “Where structure is learned, it is usually learned outside of training through neural architecture search (NAS)”
- Overparameterized: Having more parameters or computational capacity than is strictly necessary for a task. “we start Model Carving from an overparameterized Transformer”
- Pass@: The fraction of problems solved by at least one of generated samples. “the fraction of problems that at least one of samples solves”
- Perplexity: A language-model evaluation metric related to the exponentiated average negative log-likelihood. “reordering sublayers alone can improve perplexity”
- Power law: A mathematical relationship in which one quantity varies as a constant times a power of another. “the loss is well described by a power law in tokens”
- Proximal update: An optimization update that incorporates a penalty or constraint, often followed by projection or clipping. “We apply our rule with one change to the Adam step”
- Quantization: Representing model parameters or activations with lower numerical precision to reduce memory or computation. “its lead is robust to weight quantization”
- Residual stream: The sequence of representations carried through Transformer layers and modified by residual additions. “each sublayer writes to the residual stream”
- Rotary position encoding: A positional encoding method that represents token positions through rotations applied to query and key vectors. “rotary position encoding”
- Scaling law: An empirical relationship describing how model performance changes with scale, data, or compute. “We fit scaling laws for Model Carving and calculate the compute-optimal point”
- State-space layer: A neural-network layer based on state-space sequence modeling rather than self-attention. “Jamba interleaving attention and state-space layers”
- Structural pruning: Removing complete architectural components, such as layers or sublayers, rather than individual weights. “whole layers of trained LLMs can be removed with modest degradation”
- Topology: The structural organization and connectivity of a neural network. “we introduce Model Carving, which learns both a Transformer’s weights and its architecture”
- Weight tying: Reusing the same parameters across multiple layers or repeated computational steps. “a looped Transformer is weight-tied across depth”
- Width pruning: Reducing the dimensionality of neural-network layers or their hidden representations. “Minitron-style width pruning cuts the hidden and MLP widths uniformly”
- Weight decay: A regularization technique that discourages large parameter values by shrinking weights during optimization. “with nanochat's default learning rates”





