Refactoring Code Through Library Design

NeurIPS 2026

Contents

  1. 1. What makes a good refactoring?
  2. 2. How well does Librarian scale with sample size?
  3. 3. Can’t my agent just do this?
  4. 4. Example: Hugging Face Transformers
[Paper]first page of the paper
file_1file_2file_3Files with duplicated codesimilar functionssimilar classeslibrarysrc 1src 2src 3MDL −12%librarysrc 1src 2src 3MDL −18%librarysrc 1src 2src 3MDL −31%librarysrc 1src 2src 3MDL −27%coding agent1Sample many refactorings2Remove samplesthat fail tests3Keep lowest MDLLibrary + refactored sourcessource 1source 2source 3librarydef rope(...)class Attentionnew.pyshorter sources,less duplicationnew sources, writtenwith the library

Tl;dr: Librarian refactors a set of files into a shared library. It samples many refactorings, drops the ones that fail the tests, and keeps the one with the lowest MDL. In a user study, people preferred MDL’s pick over Maintainability Index’s 67% of the time. On Hugging Face Transformers, Librarian’s library has 15 functions used about 100 times; Claude Code’s has 7, used 41 times.

Abstract

Maintainable and general software allows developers to build robust applications efficiently, yet achieving these qualities often requires refactoring specialized solutions into reusable components. This challenge becomes particularly relevant as code agents are increasingly used to solve isolated one-off programming problems. We investigate code agents’ capacity to refactor code in ways that support consolidation and reusability. We first investigate what makes a good refactoring, finding via simulation results and a human study that proxies of program size, such as Minimum Description Length, better predict preferable refactorings than extant software engineering metrics, such as Maintainability Index. We then present Librarian, a method that combines divide-and-conquer with sample-and-rerank to generate reusable libraries. We compare Librarian to state-of-the-art library generation methods, and study it on real-world Python programs.

What makes a good refactoring?

Lines of code?Number of tokens?
We find MDL is best aligned with human preferences.
0%25%50%75%67%MDL over MI61%Tokens over MI56%MDL over Tokensno preferencehow often people preferred the first one
MDL=−log pLM(library)how likely the library is−Σ log pLM(source | library)how likely each source is, given the library

129 judgments from 14 people. MI = Maintainability Index.

How well does Librarian scale with sample size?

Pick the sample with thelowest MDLfewest tokenshighest MIlowest CC
MDL ↓−30%−20%−10%0+10%+20%11020304050samples% vs. original code+11%+7%−16%−21%uses per function ↑−10%0+10%+20%+30%11020304050samples% vs. one sample+27%+10%+1%0total library uses ↑−20%−10%0+10%11020304050samples% vs. one sample+8%+1%−4%−19%

Can’t my agent just do this?

Claude Code builds a library with 7 functions, used 41 times. Librarian samples from Claude Code and builds one with 15, used ≈100 times.

On the Hugging Face Transformers files. We asked Claude Code once to “reduce code duplication by extracting shared code into a library”.

Example: Hugging Face Transformers

BeforeLibraryAfterdef apply_rotary_pos_emb(q, k, ...): # ... 15 lines of RoPE ...class BaseAttention(nn.Module): def __init__(self, config, layer_idx): # Generalizes over bias and sliding window attention_bias = getattr( config, 'attention_bias', False) if hasattr(config, 'layer_types'): qkv_bias = True # Qwen2 style if (config.layer_types[layer_idx] == "sliding_attention"): self.sliding_window = config.sliding_window self.q_proj = nn.Linear(..., bias=qkv_bias) ... def forward(self, hidden_states, ...): # ... standard attention logic ... return self.o_proj(attn_output)class BaseDecoderLayer(nn.Module): def __init__(self, config, layer_idx, attention_class, mlp_class, norm_class): # Composes all modules passed as arguments self.self_attn = attention_class(config, ...) self.mlp = mlp_class(config) ... def forward(self, hidden_states, ...): # Self Attention Block residual = hidden_states hidden_states = self.self_attn(...) hidden_states = residual + hidden_states ... # MLP Block return hidden_states# Other components...library.py372 linesdef apply_rotary_pos_emb(q, k, ...): # ... 24 lines of RoPE ...class Qwen2Attention(nn.Module): def __init__(self, config, layer_idx): # NOTE: bias=True for q, k, v self.q_proj = nn.Linear(..., bias=True) ... self.o_proj = nn.Linear(..., bias=False) # NOTE: Qwen2-specific sliding window self.sliding_window = ( config.sliding_window if ...) # ... 61 lines of implementation ...class Qwen2DecoderLayer(nn.Module): # ... 45 lines of implementation ...modeling_qwen2.py498 linesdef apply_rotary_pos_emb(q, k, ...): # ... 15 lines of RoPE ...class LlamaAttention(nn.Module): def __init__(self, config, layer_idx): # NOTE: bias depends on config self.q_proj = nn.Linear(..., bias=config.attention_bias) ... # NOTE: No sliding window logic # ... 52 lines of implementation ...class LlamaDecoderLayer(nn.Module): # ... 55 lines of implementation ...modeling_llama.py505 linesfrom .library import ( BaseAttention, BaseDecoderLayer, apply_rotary_pos_emb, ...)Qwen2Attention = BaseAttentionclass Qwen2DecoderLayer(BaseDecoderLayer): def __init__(self, config, layer_idx): super().__init__( config, layer_idx, attention_class=Qwen2Attention, mlp_class=BaseMLP, ...)modeling_qwen2.py498 → 294 linesfrom .library import ( BaseAttention, BaseDecoderLayer, apply_rotary_pos_emb, ...)LlamaAttention = BaseAttentionclass LlamaDecoderLayer(BaseDecoderLayer): def __init__(self, config, layer_idx): super().__init__( config, layer_idx, attention_class=LlamaAttention, mlp_class=BaseMLP, ...)modeling_llama.py505 → 296 linesshared functionshared classshared classdirect reuseenables sliding_windowinheritancestandard attention−41%lines in each file

All integration tests still pass.

BibTeX

@inproceedings{kovacic2026refactoring,
  title     = {Refactoring Code Through Library Design},
  author    = {Kova{\v{c}}i{\v{c}}, {\v{Z}}iga and Chiu, Justin T. and Lee, Celine
               and Zhao, Wenting and Ellis, Kevin},
  booktitle = {Advances in Neural Information Processing Systems},
  year      = {2026}
}