← All skills

gencdr

models

Generate antibody, nanobody and paired heavy-light CDRs on a framework prompt with GenCDR on CPU — IgGenCDR, NanoGenCDR and p-IgGenCDR weights, region log-likelihoods, and the three API silences that return plausible nonsense.

GenCDR — generate antibody and nanobody CDRs on a framework prompt

Most antibody sequence models write residues left to right, so a CDR is generated before the frameworks that follow it are visible. GenCDR inverts that: all four framework regions are the prompt, and all three CDRs are the response, generated jointly. The practical consequence is that CDR design becomes infilling against a scaffold you have already chosen — a humanised framework, a germline, the framework of an antibody already in your pipeline — and that CDR likelihood is separable from framework likelihood, which is what makes scoring and preference alignment well defined.

Three checkpoints were released, all the same shape — a decoder-only LLaMA, 4 layers, hidden size 768, 25,246,464 parameters, a 48-token vocabulary — and all small enough to run on a laptop CPU:

model name chains trained on archive
iggencdr one conventional chain, heavy or light ~254M unpaired human OAS sequences 93.8 MB
nanogencdr nanobody / VHH, heavy only ~6.5M INDI VHH sequences, fine-tuned from IgGenCDR 93.8 MB
p-iggencdr cognate heavy and light, jointly ~1.8M paired OAS sequences, fine-tuned from IgGenCDR 93.8 MB

What this page does not cover, because other pages own it. Segmenting a raw variable domain into frameworks and CDRs under IMGT, Kabat or Chothia — GenCDR needs the frameworks already split out, and antibody-numbering is where the scheme boundaries live. Designing CDRs on a fixed structure rather than a sequence scaffold is antifold. Folding the result is immunebuilder; humanness scoring is biophi; real framework and CDR sequences to use as scaffolds come from sabdab.

Licence and access

Everything on this page is open, and nothing needs an account, a token or a click-through.

  • Code — Apache-2.0. The repository carries an Apache License 2.0 LICENSE.
  • Weights — Apache-2.0. The release notes for v1.0.0 (published 2026-10-25) read: "IgGenCDR, NanoGenCDR, and p-IgGenCDR model weights, released under Apache-2.0." The repository README says the same of the three archives.
  • Download — anonymous. The three archives are release assets on a public repository, fetched over plain HTTPS by the package itself. No GPU is needed for anything here.

Pin the code and the weights separately

They are not the same pin, and the obvious reading of the version number is wrong.

v1.0.0 is a weights release, not a code release. The tag points at the repository's initial commit, whose checkpoints.py says in its own docstring that "HuggingFace Hub download is not yet wired up" — its download_from_hub raises NotImplementedError and resolve_checkpoint has no download path at all, so with an empty cache it raises FileNotFoundError naming a directory that was never populated. Installing the package at that tag therefore gives you code that cannot fetch the weights the tag publishes. (That is read off the tag's source, not run here; what was run is the later commit.) The automatic download landed on main the same day the weights were released.

So: pin the code to a commit, and let it fetch the weights from v1.0.0. Both blocks below that install the package pin commit bacae83 (bacae830cea2d8e2640254ef884a1f0ecfc657af, 2026-10-25), which is main as it stood when this page was written and the first commit that can download anything. The other two blocks install nothing and run against whatever is already on the path, so run them in the environment the first block builds.

The weights are integrity-checked for you, which is worth knowing because it means you do not have to do it yourself: checkpoints.py carries the SHA-256 of each archive as a literal, and refuses to populate the cache if a download does not match. A successful load is the verification.

Before the first block

  • Python 3.10 or 3.11, and nothing newer. pyproject.toml declares python = ">=3.10,<3.12". On anything outside that range pip stops before downloading, with ERROR: Package 'gencdr' requires a different Python naming your version and that range — observed here on 3.14.6, which is what Homebrew's python3 currently is. There is no workaround on this page; use a 3.11 interpreter.
  • About 1.4 GB of disk for the environment (torch is most of it) plus 96 MB per checkpoint.
  • Weights cache. Archives are unpacked to ~/.cache/gencdr/<model>/; set GENCDR_HOME to put them somewhere else. The first block below exports it and the later blocks inherit it, so a trial run leaves nothing in your home directory as long as you stay in that shell. Open a fresh terminal for a later block and it will populate ~/.cache/gencdr instead — export GENCDR_HOME again first if that matters to you.
  • No GPU. The constructor's fp=16 default is honoured only on CUDA, so a CPU or MPS load is fp32 whatever you pass. With device=None it picks CUDA, then MPS, then CPU — on a Mac that means MPS, so name device="cpu" if you want the numbers below.

Try it

Data — the heavy-chain framework set the repository publishes at examples/frameworks/heavy_vh.json (Apache-2.0, read at commit bacae83), and the iggencdr weights from release v1.0.0 (Apache-2.0, SHA-256 checked by the package against the digest compiled into it). Both were reachable anonymously on 2026-11-19.

Run — one block from an empty directory. It installs the pinned commit, writes gencdr_try.py, and generates heavy-chain CDRs on that framework prompt. The three checks after the generation are the point of the block: each one is a place where this API returns something usable-looking instead of raising, and each is explained under Three silences below.

COLD=$(mktemp -d) && cd "$COLD"
python3.11 -m venv .venv && . .venv/bin/activate
pip install -q "gencdr @ git+https://github.com/AstraZeneca/GenCDR.git@bacae830cea2d8e2640254ef884a1f0ecfc657af"
export GENCDR_HOME="$COLD/weights"

cat > gencdr_try.py <<'EOF'
# GenCDR on CPU: generate heavy-chain CDRs on a framework prompt, and check the three
# things about this API that are silent rather than loud.
import json, urllib.request
from gencdr import GenCDRGenerator, cache_root
from gencdr.tokenizer import CANONICAL_AA_ALPHABET
from gencdr import checkpoints

FW = ("https://raw.githubusercontent.com/AstraZeneca/GenCDR/"
      "bacae830cea2d8e2640254ef884a1f0ecfc657af/examples/frameworks/heavy_vh.json")
AA = set("ACDEFGHIKLMNPQRSTVWY")

# The package fetches the weights from a pinned release and refuses anything whose SHA-256
# is not the published one, so a successful load IS the integrity check.
# `_MODEL_SHA256` is underscore-private, so read it defensively: an upstream rename should
# cost one line of output, not the whole script.
digests = getattr(checkpoints, "_MODEL_SHA256", None)
print("release:", checkpoints.RELEASE_TAG, "| cache:", cache_root(),
      "| digests:", len(digests) if digests else "private name moved — check upstream")
assert checkpoints.RELEASE_TAG == "v1.0.0"

fw = json.load(urllib.request.urlopen(FW))
frameworks = {k: fw[k] for k in ("fr1", "fr2", "fr3", "fr4")}
gen = GenCDRGenerator.from_pretrained("iggencdr", device="cpu")
cfg = gen.model.config
print(f"{gen.device} | fp16={gen.use_fp16} | {sum(p.numel() for p in gen.model.parameters()):,} params "
      f"| {cfg.model_type} {cfg.num_hidden_layers}L h{cfg.hidden_size} vocab {cfg.vocab_size}")

# 1. parsed_ok is about token structure, not about getting three CDRs.
designs = gen.generate_cdrs_from_frameworks(chain_type="H", frameworks=frameworks,
                                            n_samples=16, temperature=1.0, seed=0)
parsed = [d for d in designs if d["parsed_ok"]]
usable = [d for d in parsed if d["cdr1"] and d["cdr2"] and d["cdr3"]]
print(f"\n16 samples: {len(parsed)} parsed_ok, {len(usable)} with all three CDRs non-empty")
for d in usable[:3]:
    print("  ", d["cdr1"], d["cdr2"], d["cdr3"])
# Asserting the CDRs are canonical would prove nothing: upstream rejects a non-canonical
# residue inside the predicate that produced `parsed` (generator.py appends
# `non_canonical_aa_in_*` to `issues`, and `parsed_ok` is `len(issues) == 0`), so no
# parsed_ok design can carry one. Check the alphabet that guard uses instead — that is
# falsifiable, and it fails if upstream ever widens it:
assert set(CANONICAL_AA_ALPHABET) == AA, "upstream changed its residue alphabet"
assert len(usable) < len(parsed), "every parsed_ok design had three CDRs — see silence 1"

# 2. `scheme` is a no-op unless the generator was built with include_scheme_token=True.
#    An unknown scheme name is accepted in silence by the default loader.
a = gen.generate_cdrs_from_frameworks(chain_type="H", frameworks=frameworks, n_samples=2,
                                      scheme="imgt", seed=1)
b = gen.generate_cdrs_from_frameworks(chain_type="H", frameworks=frameworks, n_samples=2,
                                      scheme="not-a-scheme", seed=1)
assert [d["text"] for d in a] == [d["text"] for d in b], "scheme reached the prompt after all"
print('scheme="imgt" and scheme="not-a-scheme" are byte-identical with the default loader')

keyed = GenCDRGenerator.from_pretrained("iggencdr", device="cpu", include_scheme_token=True)
c = keyed.generate_cdrs_from_frameworks(chain_type="H", frameworks=frameworks, n_samples=2,
                                        scheme="imgt", seed=1)
assert [d["text"] for d in c] != [d["text"] for d in a], "the scheme token changed nothing"
for bad in (None, "not-a-scheme"):
    try:
        keyed.generate_cdrs_from_frameworks(chain_type="H", frameworks=frameworks,
                                            n_samples=1, scheme=bad, seed=1)
        raise AssertionError(f"scheme={bad!r} was accepted with the token enabled")
    except KeyError as e:
        print(f"include_scheme_token=True, scheme={bad!r} -> KeyError: {e}")

# 3. Nothing checks that the checkpoint belongs to the call. A paired call on the
#    single-chain model returns confident-looking heavy and light CDRs.
wrong = gen.generate_paired_cdrs_from_frameworks(
    h_frameworks=frameworks,
    l_frameworks={"fr1": "DIQMTQSPSSLSASVGDRVTITC", "fr2": "WYQQKPGKAPKLLIY",
                  "fr3": "GVPSRFSGSGSGTDFTLTISSLQPEDFATYYC", "fr4": "FGQGTKVEIK"},
    n_samples=2, seed=0)
print("paired call on the single-chain checkpoint:",
      [(d["parsed_ok"], d["H"]["cdr3"], d["L"]["cdr3"]) for d in wrong])
assert any(d["parsed_ok"] for d in wrong), "upstream added a guard — good news, update this page"

# A design's likelihood under the model, split by region.
item = dict(chain_type="H", fr1=frameworks["fr1"], cdr1=usable[0]["cdr1"],
            fr2=frameworks["fr2"], cdr2=usable[0]["cdr2"],
            fr3=frameworks["fr3"], cdr3=usable[0]["cdr3"], fr4=frameworks["fr4"])
# reduction defaults to "mean", so these are per-residue averages, not sequence totals.
regions = gen.batch_log_likelihood_regions_from_segments([item])
print("mean per-residue log-likelihood:", {k: round(v[0], 4) for k, v in regions.items()})
assert set(regions) == {"full", "framework", "cdr"} and all(v[0] < 0 for v in regions.values())
EOF

python gencdr_try.py

Expect — invariants, true of any version, so a failure means this page is wrong:

  • the release tag the package fetches from is v1.0.0;
  • 25,246,464 parameters, a 4-layer LLaMA with hidden size 768 and a 48-token vocabulary;
  • the alphabet upstream's non-canonical-residue guard checks against is the 20 standard amino acids (asserting that the output is canonical would prove nothing — that guard sits inside parsed_ok, so no parsed design can fail it);
  • at least one parsed_ok design is missing a CDR, which is silence 1 below;
  • with the default loader, scheme="imgt" and scheme="not-a-scheme" produce byte-identical text, and with include_scheme_token=True both an unknown scheme and None raise KeyError;
  • a paired call on the single-chain checkpoint returns parsed_ok designs rather than raising;
  • the three region values are all negative. They are mean per-residue log-likelihoods, not sequence totals: reduction defaults to "mean", and reduction="sum" gives totals. Rank designs of differing CDR length on sums, or the shorter CDR wins on the mean alone.

Observed on 2026-11-19 (seed=0 is deterministic on CPU — this output reproduced exactly on a re-run, so the sequences are a version-stamped observation and will move when torch or transformers does, not a bug):

release: v1.0.0 | cache: /tmp/tmp…/weights
cpu | fp16=False | 25,246,464 params | llama 4L h768 vocab 48

16 samples: 16 parsed_ok, 13 with all three CDRs non-empty
   AYYMS DISSSGSTIYYADSVKG SSGWSYFDY
   CYGMH VISYDGNNKYYADSVKG SPAELWFGEFDFDY
   TYAMS AISGSGGSTYYADSVKG DSGSSSL
scheme="imgt" and scheme="not-a-scheme" are byte-identical with the default loader
include_scheme_token=True, scheme=None -> KeyError: None
include_scheme_token=True, scheme='not-a-scheme' -> KeyError: 'not-a-scheme'
paired call on the single-chain checkpoint: [(True, 'QQGLYSNPMYYFDY', 'QQSHNTPLT'), (True, 'ARAPSGYALRY', 'QQSYSTPT')]
mean per-residue log-likelihood: {'full': -0.4807, 'framework': -0.3638, 'cdr': -0.7899}

Generation itself is cheap: measured here, a warm load is 0.13 s, 16 samples 0.76 s and 64 samples 1.09 s on CPU. The cost is all setup — the 93.8 MB archive, and roughly a gigabyte of wheels. The block above took five minutes end to end on a cold weights cache, plus the pip install.

Three silences

Each of these returns a plausible object instead of an error, which is the only reason they are worth a section. An agent that filters on parsed_ok and trusts its arguments will ship designs that are not what it asked for.

1. parsed_ok means the token stream parsed, not that you have three CDRs. A design can have parsed_ok: True, no issues, and an empty string for a CDR. Measured over 96 samples on the example heavy framework (6 seeds x 16), 0 were parsed_ok: False and 13 had at least one empty CDR. The CLI writes the same rows: its full_sequence column then concatenates FR1 straight onto FR2, giving a 113-residue variable domain with no CDR1 at all, and parsed_ok still reads True. Filter on the CDRs themselves, as the block above does. Where parsed_ok is False, issues names the reason — under_sep and over_sep, meaning the wrong number of <SEP> tokens came back.

2. scheme= does nothing unless you built the generator with include_scheme_token=True. The constructor defaults it to False, and in that mode the scheme never reaches the prompt: "imgt", "kabat", "chothia", None and an invented name all yield identical output, as the block above asserts. Upstream's own quickstart passes scheme="imgt" with the default constructor, so the argument reads as load-bearing when it is inert. Turn the token on and it does change the output materially, and an unknown scheme then raises instead of passing. Which mode matches the published results is not stated upstream and is not resolved here — if you care, the safe reading is that the default mode is what upstream's examples exercise.

3. Nothing ties a checkpoint to a call. Weights, config and tokenizer are identical in shape across the three releases, so the loader cannot tell them apart and does not try. Observed: a paired call on iggencdr returned four parsed_ok heavy-and-light designs; a single-chain call on p-iggencdr returned four parsed_ok designs; nanogencdr asked for a light chain returned three over_sep failures and one "successful" design with a 25-residue CDR2. The model name you pass is the only guard there is. Related: resolution is case-insensitive and aliased — nano, paired, piggencdr and IgGenCDR all resolve — so a typo that happens to be an alias will load a different model without comment.

Two more that do fail loudly, for completeness: a missing framework key raises KeyError: 'fr2', and lowercase framework sequences are accepted but tokenise as something else, producing unrelated CDRs and occasional parse failures. Upper-case your input.

Nanobodies and paired chains

Same cache, same device argument, one archive each. Run this in the Try it directory:

# NanoGenCDR on a VHH framework, and p-IgGenCDR generating six CDRs in one pass.
import json, urllib.request
from gencdr import GenCDRGenerator

B = ("https://raw.githubusercontent.com/AstraZeneca/GenCDR/"
     "bacae830cea2d8e2640254ef884a1f0ecfc657af/examples/frameworks/")
vhh = json.load(urllib.request.urlopen(B + "nanobody_vhh.json"))
pair = json.load(urllib.request.urlopen(B + "paired_hl.json"))

nano = GenCDRGenerator.from_pretrained("nanogencdr", device="cpu")
designs = nano.generate_cdrs_from_frameworks(
    chain_type="H", frameworks={k: vhh[k] for k in ("fr1", "fr2", "fr3", "fr4")},
    n_samples=6, seed=0)
for d in designs:
    if d["cdr1"] and d["cdr2"] and d["cdr3"]:
        print("VHH ", d["cdr1"], d["cdr2"], d["cdr3"])

pm = GenCDRGenerator.from_pretrained("p-iggencdr", device="cpu")
for order in ("L-first", "H-first"):
    out = pm.generate_paired_cdrs_from_frameworks(h_frameworks=pair["H"], l_frameworks=pair["L"],
                                                  n_samples=3, order=order, seed=0)
    # a paired result is nested: d["H"] and d["L"] each carry their own parsed_ok
    good = [d for d in out if d["parsed_ok"]]
    print(f"{order}: {len(good)}/{len(out)} parsed", [(d["H"]["cdr3"], d["L"]["cdr3"]) for d in good])

Observed on 2026-11-19, nanogencdr on the example VHH framework and p-iggencdr on the example pair, 6 of 6 and 3 of 3 parsed:

VHH  GYAMG GINRYGSSTYYADSVKG QAGSWFGFDFLISNYDY
VHH  IYAMG AISWSGSNTYYADSVKG ATYRHDGLALIGEYDY
VHH  LATMG AISRSGSSTYYADSVKG AKYRHDGLALIGEYDY
L-first: 3/3 parsed [('SLGPNIAAAGTDYFQH', 'QQSYSTPQT'), ('AKGDYYYDSSGYYLDY', 'QQSYSTPVT'), ('DPGRGLYGLDY', 'QQSYSTPQT')]
H-first: 3/3 parsed [('DRVRGNSGWYYFDY', 'QQSYSTPQT'), ('DFGSSGAEDY', 'QQSYSTPQT'), ('ETTYSGTYLDY', 'QQSYSTPVT')]

A paired result has a different shape from a single-chain one — {"text", "order", "H", "L", "parsed_ok", "issues"}, with a nested parsed_ok per chain as well as the top-level one, which is True only when both chains parsed. order decides which chain is generated first and therefore which one is conditioned on the other's CDRs; both directions are supported and they give different designs from the same seed.

The command line, and the dependency that breaks it

The package installs a gencdr command with four subcommands — generate, generate-paired, score, align. As of 2026-11-19 it does not work on a fresh install, because nothing pins click: gencdr --help dies with TypeError: Parameter.make_metavar() missing 1 required positional argument: 'ctx', and every --option value pair is read as a positional, so gencdr generate --model iggencdr … fails with Got unexpected extra arguments (iggencdr heavy_vh.json H 4 designs.csv). The pin is typer ^0.12.5, and typer 0.12 predates click 8.2's signature change.

One extra pin fixes it, and the CSV it writes is the most convenient output this tool has:

Run it in the Try it directory, inside that venv — click<8.2 is a downgrade, and outside the venv it would demote click for every other tool sharing that environment:

set -e
cd "$COLD" && . .venv/bin/activate
pip install -q "click<8.2"
curl -fsSLO https://raw.githubusercontent.com/AstraZeneca/GenCDR/bacae830cea2d8e2640254ef884a1f0ecfc657af/examples/frameworks/heavy_vh.json
gencdr generate --model iggencdr --frameworks heavy_vh.json --chain-type H \
    --n-samples 4 --out-csv designs.csv

Observed: Generated 4 sequences (4 parsed_ok) from 1 framework set(s) -> designs.csv, and a designs.csv with one row per sample and the columns id, chain_type, sample_idx, fr1, fr2, fr3, fr4, cdr1, cdr2, cdr3, full_sequence, parsed_ok, sep_count, issues. Read that file with silence 1 in mind: one of those four rows had an empty cdr1 and parsed_ok reading True.

gencdr score on raw, unsegmented sequences is the one subcommand this page cannot offer, for a reason that is not the click pin — see What does not work.

Steering generation with your own rewards — not run

The framework-prompt / CDR-response split is what makes preference optimisation well defined here: the objective can be applied to CDR-response tokens only, against a frozen reference policy, with samples compared inside scaffold groups. You supply a CSV of designs with a scalar reward column — binding, expression, developability, a structural score, an assay readout — and a meta_framework_source label grouping designs that share a scaffold, plus the framework and CDR columns. Upstream publishes an example CSV at examples/rewards/single_rewards.csv and documents the schema in its README. Note that --reward-csv below is your file: the git install brings no examples/ tree, so nothing puts upstream's copy on disk. Fetch it with curl -fsSLO https://raw.githubusercontent.com/AstraZeneca/GenCDR/bacae830cea2d8e2640254ef884a1f0ecfc657af/examples/rewards/single_rewards.csv if you want to read the schema, but see below for why training on it is pointless.

set -e
pip install -q "gencdr[align] @ git+https://github.com/AstraZeneca/GenCDR.git@bacae830cea2d8e2640254ef884a1f0ecfc657af"
gencdr align --model iggencdr --reward-csv your_rewards.csv \
    --output-dir aligned --beta 0.15 --max-epochs 5 --batch-size 16

This was not run here, and the reason is about the data rather than the compute: a reward column has to come from a downstream objective, and training against the example file's numbers would produce a checkpoint that optimised nothing real. Two things to know before you try it: the aligned weights are written to --output-dir and are not shipped with the package, and the best checkpoint is selected by validation Spearman correlation between CDR likelihood and reward, which means a reward column with little rank information will select essentially arbitrarily. --paired aligns p-iggencdr from meta_h_* / meta_l_* columns.

What does not work

  • pip install gencdr — there is no gencdr on PyPI (the JSON API answers 404), so this fails on every Python version with No matching distribution found. Install from the git URL, as every block here does. That path is the one with the version constraint: on 3.12 or newer it refuses at metadata, see Before the first block. Use 3.10 or 3.11.
  • Installing the package at tag v1.0.0 — that tag is the weights release and points at the initial commit, which cannot download weights. Pin a commit on main.
  • The gencdr CLI on a fresh install — the click incompatibility above. pip install "click<8.2".
  • gencdr score on raw sequences, and the scoring extra generally. It needs FR/CDR segmentation from abnumber, pinned to a git revision. Pip resolves and installs it, and then the import prints ANARCI module not available. Please install it separately or install AbNumber through Bioconda — ANARCI needs a HMMER binary that pip does not deliver. Segment with antibody-numbering instead, which installs from PyPI, and feed GenCDR the regions; log_likelihood_from_segments and batch_log_likelihood_regions_from_segments need no extra at all and are what gencdr score wraps.
  • scheme= with the default constructor — inert, see Three silences.
  • Mixing a checkpoint and a call — never raises, see Three silences.
  • Lowercase framework sequences — accepted, and wrong.

Limits worth stating plainly

  • GenCDR conditions on frameworks and nothing else. There is no antigen, no epitope and no structure anywhere in the input, so what it generates is a CDR that looks like a plausible CDR on that scaffold, not a CDR that binds your target. Binding has to come from a downstream filter or from the alignment loop above.
  • The training corpora are human OAS and camelid INDI repertoires. Designs are drawn towards what those repertoires contain, which is a reasonable prior for developability and a poor one for anything deliberately unusual.
  • The three checkpoints cover one conventional chain, a VHH, and a cognate pair. Anything else — a TCR, a scFv linker, an engineered format — is outside what was trained, and nothing in the code will tell you so.
  • Cysteines appear in generated CDRs — 1 of the 13 usable designs in this page's own 16-sample run carried one. An unpaired cysteine in a CDR is a developability problem, and GenCDR has no view on it.
  • Sampling is unconditional on quality: temperature and top_p are the only levers in generate_cdrs_from_frameworks, and designs come back missing a CDR at a rate worth budgeting for — 3 of 16 in this page's run, 13 of 96 across six seeds. Generate more than you need and filter.