Kermt Continue Pretrain
NVIDIAOfficialPublished by NVIDIA
- Skill
- Workflow
- Data and AI
- Apache-2.0
- Medium risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The kermt-continue-pretrain skill manages the end-to-end workflow for continuing the pretraining of KERMT models (grover_base, cmim, or hybrid). It handles input validation, data preparation, and the execution of training runs within a containerized environment. The skill supports both fresh-schedule training and true resumption of interrupted runs, ensuring that model architecture and vocabulary constraints are strictly maintained.
What it does
- Validates system requirements and GPU availability for training.
- Resolves and validates user-provided or released KERMT checkpoints.
- Prepares custom SMILES data for training while enforcing vocabulary consistency.
- Configures and launches detached training runs with hyperparameter overrides.
- Provides progress monitoring and logging for long-running training tasks.
- Generates a manifest for reproducible training runs.
When to use it
- When you need to continue training an existing KERMT checkpoint on a new SMILES dataset.
- When you want to perform a fresh-schedule continuation of a pretrained model.
- When you need to resume an interrupted training run from a specific checkpoint.
- When you want to leverage NVIDIA-released pretrained hybrid models for further training.
Advantages
- Ensures architectural and vocabulary integrity by validating checkpoints before training.
- Automates complex data preparation and container orchestration.
- Supports flexible hyperparameter tuning while preventing invalid configuration overrides.
- Provides clear error handling and redirection to appropriate workflows for incompatible models.
Usage examples
- “Continue pretraining the hybrid model on my custom_data.csv.”
- The agent will prompt for consent to download the released hybrid model, validate the CSV, prepare the data, and launch the training process.
- “Resume my interrupted pretraining run from /path/to/checkpoint.pt.”
- The agent will validate the checkpoint for resume compatibility and restart the training process from the exact state saved in the checkpoint.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/nvidia/kermt-continue-pretrain/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip kermt-continue-pretrain.zip -d .agents/skills
Documentation by NVIDIA
kermt-continue-pretrain
Continue pretraining from a user-supplied KERMT checkpoint (grover_base / cmim / hybrid). The skill is the workflow orchestrator: it validates inputs, prepares the corpus, launches the runner, and returns a run directory.
Skill and runtime paths
Set SKILL_DIR to the absolute path of this installed skill directory. Export
KERMT_REPO as the absolute path to the KERMT checkout used for model
execution. The bundled container helper mounts that checkout at
/workspace and this skill at /skill (read-only). Commands inside
the container use /skill/scripts/; defaults are bundled in config/.
See Released models for checkpoint bundle requirements.
Downloads and local outputs
The optional released-model branch reads config/released_model.json for the
Hugging Face repository, pinned revision, and filenames. The bundled
scripts/fetch_released_model.py downloads the model bundle over HTTPS into
the host directory the user selects. Public models work without credentials;
if HF_TOKEN is set, the container helper forwards it for Hugging Face
authentication. Prepared data, logs, and workflow results go into the chosen
run directory.
Hardware requirements
GPUs: 1–N CUDA-capable NVIDIA GPUs. The runner auto-detects via
torch.cuda.device_count();--gpus 0,2overrides. On a single GPU the runner falls back to--batch_size 32 --save_interval 500; on multi-GPU it uses thedefaults_pretrain.jsonvalues (currentlybatch_size 256). Note:--gpus Nuses torch.cuda indexing, which can differ fromnvidia-smi's display order on multi-GPU hosts (PCI bus vs. CUDA enumeration). To target a specific physical GPU, setCUDA_VISIBLE_DEVICESbefore invoking, or runpython -c "import torch; print([torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())])"to confirm which device you're picking.VRAM: the default
--batch-size 256is sized for A100-class hardware (80 GB VRAM). On smaller GPUs, downscale to avoid OOM:GPU class VRAM Suggested --batch-sizeL4, T4, V100 16 GB 16–24 GB 32–64 A100 40 GB, L40, A40 40–48 GB 128 A100 80 GB, H100, H200 80 GB 256 (default) These are rough starting points — pass
--batch-size Nto override.Disk: tens of GB depending on corpus size + epochs (each checkpoint is several hundred MB).
Driver / CUDA: any host supporting CUDA 12.6 (the kermt image base).
kermt-setupvalidates this up-front.
Inputs
Required:
--csv <path>— the pretrain CSV (single columnsmiles). If you have separate train/val CSVs, pass--val-csv <path>too.
Checkpoint (optional — defaults to the released model if omitted):
--ckpt <path>— the input pretrain checkpoint to continue from. Must be a grover_base (with vocab heads), cmim, or hybrid ckpt; the validator rejects everything else with a redirect to the correct workflow. If omitted, the skill offers to download the released pretrained hybrid model nvidia/NV-KERMT-70M-v2 and continue-pretrain from it — see "Resolve & validate the checkpoint" (workflow step 3). The released bundle ships its three vocab files alongside the ckpt, so the authoritative-vocab pass-through (step 5) works automatically.--pretrained-release— explicit opt-in to use the released model without the interactive prompt (for non-interactive / agent runs). Mutually exclusive with--ckpt.--model-dir <dir>— where to save the downloaded bundle (default$KERMT_REPO/models/NV-KERMT-70M-v2/). An already-complete bundle there is reused, not re-downloaded.
Optional:
--val-csv <path>— separate validation CSV. Without it, the prep step auto-splits the input by--val-frac 0.1(random shuffle with--seed).--epochs N/--batch-size N/--init-lr F/--max-lr F/--final-lr F/--warmup-epochs F/--weight-decay F/--dropout F/--save-interval N/--seed N— training-hyperparameter overrides. Anything not given is filled fromconfig/defaults_pretrain.json.--vocab-loss-weight F(hybrid only) /--latent-dim N/--contrastive-temperature F(cmim and hybrid only) — loss / decoder overrides.--wandb-project NAME/--wandb-run-name NAME— optional Weights & Biases logging. When--wandb-projectis set, rank 0 logs train/val losses; the run name is honored only alongside a project. Off by default. (Independent of the ckpt'swandb_run_idcontinuity handling under--resume.)--resume— see "Modes" section below.--gpus 0,2— restrict to a GPU subset. Default uses all visible GPUs.--from-prepare <dir>— skip the prepare step and reuse an existingprepare_data.jsonin<dir>. Useful when iterating on hyperparameters.
Modes
The runner has two modes for ingesting the input ckpt, dispatched on whether
--resume is set. Pick based on intent:
Default (fresh-schedule continue-pretrain)
Use when: you have a finished pretrain ckpt and want to continue training it — on a new corpus, with a different objective, or just for more epochs than its original plan. The previous training's step counter and schedule shape are no longer relevant; you want a new learning-rate schedule for the new run.
What gets loaded from the ckpt:
✓ Model weights (encoder + vocab heads + contrast head + decoder, whatever is there)
✓ Optimizer state (Adam's running m1/m2 moments — warm-starts the new schedule so the first few hundred steps aren't dominated by noisy gradient-estimate startup)
✗ Scheduler step counter (reset to 0)
✗ Epoch counter (reset to 0)
✗ Batch counter (reset to 0)
✗ wandb run id (new wandb run, not a continuation)
Schedule shape (init/max/final LR, warmup epochs, total epochs): from
your CLI args or defaults_pretrain.json. A fresh NoamLR is constructed
from these values and starts at step 0.
--resume (true resume)
Use when: a previous run was interrupted (crash, OOM, Ctrl-C) and you want to pick up exactly where it left off — same dataset, same schedule, same training trajectory.
What gets loaded from the ckpt: everything in the
save_model_for_restart format. Model weights + optimizer state +
scheduler_step + epoch + batch_idx + wandb_run_id are all restored. The
new run continues from the saved step in the saved schedule (which is
recovered from the ckpt's saved_args). Mid-epoch resume works too —
pretrain_ddp.py's sampler skip-count picks up at the saved batch index
within the saved epoch.
Schedule shape: inherited from the ckpt's saved_args. CLI overrides
of any schedule flag (--epochs / --warmup-epochs / --init-lr / --max-lr / --final-lr) are rejected with a hard error — pure resume means pure
resume; if you want to change the schedule, drop --resume and start a
fresh-schedule run.
Requirements: the ckpt must have been saved via save_model_for_restart
(i.e., carry optimizer / scheduler_step / epoch / batch_idx keys). If
any of these is missing, the runner errors with a clear message and
suggests dropping --resume.
The default mode is the right choice ~90% of the time. Reach for --resume
only when you genuinely need to continue a single interrupted training
run.
Workflow
Let $KERMT_REPO be the path to your kermt repo checkout, and assume
kermt-setup has already built kermt:latest. All paths below are on the
host; the helper bind-mounts them at known container paths.
Pre-flight: ensure container + system probe.
"$SKILL_DIR/scripts/kermt_container.sh" check_system | python -c " import json, sys; d = json.load(sys.stdin) if not d['ok']: print('System check failed:', d['gaps']); sys.exit(1) print(f'OK: {len(d[\"gpus\"])} GPU(s); {d[\"disk\"][\"free_gb\"]} GB free; CUDA via container toolkit') "Surface any
gapsto the user. Refuse to proceed ifok: false.Compute run directory.
RUN_DIR=$KERMT_REPO/runs/continue-pretrain_$(date -u +%Y-%m-%dT%H-%M-%SZ)Resolve & validate the checkpoint.
Resolve — only if
--ckptwas omitted. Default to the released pretrained hybrid model nvidia/NV-KERMT-70M-v2:Consent gate. Unless
--pretrained-releasewas passed, ask the user: "No checkpoint given — download the released model nvidia/NV-KERMT-70M-v2 (NVIDIA Open Model License, https://huggingface.co/nvidia/NV-KERMT-70M-v2) and continue-pretrain from it? [y/N]". Never download without an explicit yes (or--pretrained-release). If both--ckptand--pretrained-releaseare given, abort — they conflict.Save location. Default
$KERMT_REPO/models/NV-KERMT-70M-v2/; honor--model-dir <dir>if given. An already-complete bundle is reused.Download (foreground; ~282 MB on first fetch):
"$SKILL_DIR/scripts/kermt_container.sh" run --model-dir <save-dir> -- \ "python /skill/scripts/fetch_released_model.py --out /model"Parse the JSON; abort on
ok: false(surfaceerrors). On success set<user-ckpt> = <save-dir>/kermt_contrastive_v2.0.pt. The bundle's three vocab files land in<save-dir>too, so step 5's--vocab-dirauto-detection (which looks in the ckpt's parent directory) finds them with no extra work.
Validate the resolved (or user-provided) ckpt:
"$SKILL_DIR/scripts/kermt_container.sh" run --ckpt <user-ckpt> -- \ "python /skill/scripts/check_checkpoint.py --mode continue_pretrain --ckpt /ckpt"Parse the JSON. Abort on
ok: false, showing the error verbatim. The error message redirects the user tokermt-add-cmim-pretrainfor encoder-only ckpts, or tokermt-finetunefor finetuned ckpts.Validate the data.
"$SKILL_DIR/scripts/kermt_container.sh" run --data <user-csv> -- \ "python /skill/scripts/check_data.py --mode pretrain --csv /data/<basename>"Abort on
ok: false.Prepare the data (skip if
--from-preparegiven). Pass the ckpt's vocab through. Look in the ckpt's parent directory for the conventionalpretrain_atom_vocab.{json,pkl},pretrain_bond_vocab.{json,pkl}, andpretrain_smiles_vocab.pklfiles (the bundling convention for released models; seereferences/released-models.md). If all three are present, auto-pass via--vocab-dir <ckpt_parent_dir>. If only some are present, pass them via explicit flags (--atom-vocab,--bond-vocab,--smiles-vocab). If none are present, ask the user for--vocab-dir— or refuse to proceed, because rebuilding a fresh vocab from the new corpus would silently mismatch the ckpt's vocab heads (the ckpt's vocab is authoritative for continue-pretrain).Note the two-layer mount pattern: pass the host directory to
kermt_container.sh --vocab-dir(which mounts it at/vocabinside the container), and reference/vocabfrom the innerprepare_data.pycommand. The same pattern applies to every host path the inner command needs to read (--data <host-csv>→/data/<basename>,--ckpt <host-ckpt>→/ckpt).VOCAB_DIR=$(dirname <user-ckpt>) "$SKILL_DIR/scripts/kermt_container.sh" run \ --data <user-csv> --vocab-dir $VOCAB_DIR --run-dir $RUN_DIR -- \ "python /skill/scripts/prepare_data.py --mode pretrain \\ --csv /data/<basename> --out /runs/data \\ --vocab-dir /vocab \\ [--val-csv /data/<val-basename>] [--val-frac 0.1] [--seed 0]"Outputs land at
$RUN_DIR/data/prepare_data.jsonwithvocab_source: "user_provided". The runner step 7 will verify the vocab files' entry counts match the ckpt's vocab-head sizes and refuse to launch on mismatch.Estimate runtime + confirm with user.
Pretrain wall time depends on corpus size × epochs × GPU count.
Tell the user the estimate; ask "proceed?" unless
--yesflag was given (agent-non-interactive case).Example estimate template:
~N hours on K GPUs for E epochs over M molecules (~steps/epoch × seconds/step).
Launch the runner detached.
"$SKILL_DIR/scripts/kermt_container.sh" run_detached \\ --name kermt-continue-pretrain-<ts> \\ --ckpt <user-ckpt> --run-dir $RUN_DIR -- \\ "python /skill/scripts/run_pretrain_local.py \\ --ckpt /ckpt \\ --prepare-manifest /runs/data/prepare_data.json \\ --out /runs \\ [--epochs N --batch-size N --init-lr F ...]"Returns the container name + id + log file path.
Report to the user. Output a short summary:
Container name + id
$RUN_DIR/run.json(the manifest with cmd_replay + image digest)Log file:
$RUN_DIR/logs/pretrain_ddp.logTensorBoard:
$RUN_DIR/logs/tb(open withtensorboard --logdir $RUN_DIR/logs/tb)Suggest invoking
kermt-monitor <RUN_DIR>to check progress.
Hard rules
Never download the released model without consent. When
--ckptis omitted, downloadnvidia/NV-KERMT-70M-v2only after an explicit user "yes" or an explicit--pretrained-releaseflag.--ckptand--pretrained-releaseare mutually exclusive.Never modify the user's input ckpt. The runner symlinks it into the save_dir; the symlink is what pretrain_ddp.py auto-resumes from. The source file stays untouched.
Never silently override arch. If the user passes a
--hidden-sizeetc. that doesn't match the ckpt-derived value, the runner aborts loudly. Arch params come from the ckpt, period.Never block on the long-running pretrain itself. The runner is invoked via
run_detached; the skill returns immediately after step 8. Usekermt-monitorfor progress.Echo applied defaults back to the user. The
args_appliedfield ofrun.jsonrecords every flag's value + source (user / default-config / auto-1gpu / auto-multi-gpu). Skill should surface a summary of any flag not user-specified so the user knows what was assumed.
Common errors
model_type='finetuned'rejected → the ckpt is a downstream finetune, not a pretrain. The error redirects to the relevant workflow.grover_base ckpt has no vocab head→ encoder-only ckpt (e.g. the original-grovergrover_base.pt). The error redirects tokermt-add-cmim-pretrain.prepare_data manifest is missing required outputs→ user passed--from-prepareto a directory where prepare was run with--skip-vocabor--skip-split. Re-run prepare without those flags.--gpus allnot available → installnvidia-container-toolkit; checkkermt_container.sh check_system.
Replayability
The run.json cmd_replay field is a single-line command that re-runs the
pretrain with the same inputs, hyperparameters, and arch. To replay:
# Inside the kermt container:
$(jq -r .cmd_replay $RUN_DIR/run.json)If ok_to_replay: false in the manifest (because the kermt repo working
tree was dirty at launch time), the replay may not be bit-exact — pin the
exact commit via the repo.commit field and git checkout it
first.
Files
- ATTRIBUTION.mdAdded by AutoGineer853 B
- BENCHMARK.md7.8 KiB
- LICENSELicence file added by AutoGineer11.2 KiB
- SKILL.md16.0 KiB
- config/defaults_pretrain.json2.6 KiB
- config/released_model.json398 B
- evals/evals.json7.5 KiB
- references/released-models.md1.6 KiB
- scripts/_utils.pyScript14.1 KiB
- scripts/check_checkpoint.pyScript20.1 KiB
- scripts/check_data.pyScript11.9 KiB
- scripts/fetch_released_model.pyScript7.9 KiB
- scripts/kermt_container.shScript18.9 KiB
- scripts/prepare_data.pyScript36.5 KiB
- scripts/run_pretrain_local.pyScript34.8 KiB
- skill-card.md4.6 KiB
- skill.oms.sig6.8 KiB
scripts/_utils.py
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""Shared utilities for the agent scripts.
Kept intentionally small — only logic that appears (or would otherwise be
duplicated) in two or more `scripts/*.py` modules. Each script
maintains its own primary CLI + main flow.
"""
from __future__ import annotations
import argparse
from collections import Counter
import json
import os
import pickle
import re
import shlex
import subprocess
import sys
from pathlib import Path
from typing import Any
# Conventional pretrain vocab filename stems. Used by prepare_data.py +
# upgrade_to_hybrid.py + the README "Released models" bundling docs +
# the test helpers. Centralized here so a future rename only touches one
# spot.
PRETRAIN_VOCAB_STEMS = {
"atom": "pretrain_atom_vocab",
"bond": "pretrain_bond_vocab",
"smiles": "pretrain_smiles_vocab",
}
def resolve_kermt_repo() -> Path:
"""Find the runtime checkout independently of the installed skill location.
An explicit KERMT_REPO takes precedence. In a repository checkout, walking
up from this helper or the working directory also supports local use.
"""
explicit = os.environ.get("KERMT_REPO")
if explicit:
candidates = [Path(explicit).expanduser().resolve()]
else:
candidates = []
for start in (Path(__file__).resolve().parent, Path.cwd()):
candidates.extend((start, *start.parents))
for candidate in candidates:
if (candidate / "main.py").is_file() and (candidate / "kermt").is_dir():
return candidate
raise FileNotFoundError(
"KERMT checkout not found. Set KERMT_REPO to the checkout containing "
"main.py and kermt/; the installed skill directory is separate."
)
def load_json(path: Path, *, name: str) -> dict[str, Any]:
"""Load a JSON file with consistent error messages.
`name` is a human-readable label for the document (e.g. "prepare_data.json")
so the error tells the user which schema we expected at that path.
"""
if not path.is_file():
raise FileNotFoundError(f"{name} not found at {path}")
try:
return json.loads(path.read_text())
except json.JSONDecodeError as exc:
raise ValueError(f"{name} at {path} is not valid JSON: {exc}") from exc
def count_vocab_entries(vocab_path: Path) -> int:
"""Return the number of entries in a KERMT vocab file.
Handles three layouts:
- JSON with `{stoi: {token: idx}, ...}` (MolVocab.save_vocab default)
- JSON as a raw `{token: idx}` dict (legacy / hand-edited)
- Legacy MolVocab / SMILESVocab pickles, read as inert vocabulary state.
The pickle reader accepts only the known vocabulary containers and their
Counter/regex metadata. It cannot import arbitrary classes or run reducers
supplied by the artifact, and it never falls back to an unrestricted loader.
"""
if vocab_path.suffix == ".json":
data = json.loads(vocab_path.read_text())
if isinstance(data, dict) and "stoi" in data:
return len(data["stoi"])
if isinstance(data, dict):
return len(data)
raise ValueError(f"unsupported JSON vocab shape at {vocab_path}: {type(data).__name__}")
with vocab_path.open("rb") as f:
data = _VocabUnpickler(f).load()
if isinstance(data, _VocabState) and isinstance(data.stoi, dict):
return len(data.stoi)
if isinstance(data, (dict, list, tuple)):
return len(data)
raise ValueError(f"could not count entries in {vocab_path}")
class _VocabState:
"""Data-only stand-in: counting tokens does not require tokenizer methods."""
class _VocabUnpickler(pickle.Unpickler):
def find_class(self, module: str, name: str) -> Any:
if module in {"kermt.data.torchvocab", "grover.data.torchvocab"} and name in {
"TorchVocab", "MolVocab", "SMILESVocab",
}:
return _VocabState
if (module, name) == ("collections", "Counter"):
return Counter
if (module, name) == ("re", "_compile"):
return re.compile
raise pickle.UnpicklingError(f"unsupported vocabulary object: {module}.{name}")
def load_checkpoint(path: Path | str) -> dict[str, Any]:
"""Read KERMT tensors and known metadata with PyTorch's restricted loader.
Saved arguments use argparse.Namespace; finetuned checkpoints also contain
numeric NumPy scaler arrays. Explicit globals cover those formats, including
NumPy 1/2 module names, without accepting artifact-selected imports.
"""
import numpy as np
import torch
multiarray = np._core.multiarray if hasattr(np, "_core") else np.core.multiarray
allowed = [argparse.Namespace, np.ndarray, np.dtype]
for module in ("numpy.core.multiarray", "numpy._core.multiarray"):
allowed.extend([
(multiarray._reconstruct, f"{module}._reconstruct"),
(multiarray.scalar, f"{module}.scalar"),
])
allowed.extend(type(np.dtype(name)) for name in (
"bool", "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64",
"float16", "float32", "float64",
))
with torch.serialization.safe_globals(allowed):
return torch.load(path, map_location="cpu", weights_only=True)
def runner_environment(repo: Path, *, wandb: bool = False) -> dict[str, str]:
"""Forward named runtime settings, keeping unrelated credentials out of jobs.
W&B credentials/settings are included only for an explicitly enabled W&B
run. Hugging Face authentication belongs to the separate download helper.
"""
names = (
"PATH", "HOME", "TMPDIR", "TEMP", "TMP", "LANG", "LC_ALL", "LC_CTYPE", "TZ",
"LD_LIBRARY_PATH", "LIBRARY_PATH", "CUDA_HOME", "CUDA_PATH", "PYTHONPATH",
"PYTHONDONTWRITEBYTECODE", "PYTHONUNBUFFERED", "PYTHONWARNINGS",
"CUDA_VISIBLE_DEVICES", "CUDA_DEVICE_ORDER", "CUDA_LAUNCH_BLOCKING", "NVIDIA_VISIBLE_DEVICES",
"NVIDIA_DRIVER_CAPABILITIES", "CUBLAS_WORKSPACE_CONFIG", "OMP_NUM_THREADS",
"MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMEXPR_NUM_THREADS",
"PYTORCH_CUDA_ALLOC_CONF", "PYTORCH_ALLOC_CONF", "PYTORCH_NO_CUDA_MEMORY_CACHING",
"TORCH_CPP_LOG_LEVEL", "TORCH_DISTRIBUTED_DEBUG", "NCCL_DEBUG", "NCCL_SOCKET_IFNAME",
"NCCL_IB_DISABLE", "NCCL_P2P_DISABLE", "NCCL_SHM_DISABLE", "GLOO_SOCKET_IFNAME",
"MASTER_ADDR", "MASTER_PORT",
"KERMT_REPO", "KERMT_REPO_COMMIT", "KERMT_REPO_DIRTY",
"SSL_CERT_FILE", "REQUESTS_CA_BUNDLE",
)
if wandb:
names += (
"WANDB_API_KEY", "WANDB_BASE_URL", "WANDB_MODE", "WANDB_DIR", "WANDB_ENTITY",
"WANDB_PROJECT", "WANDB_RUN_ID", "WANDB_RESUME", "WANDB_CACHE_DIR",
"WANDB_CONFIG_DIR", "WANDB_DATA_DIR", "WANDB_DISABLED",
)
env = {name: value for name in names if (value := os.environ.get(name)) is not None}
env["PYTHONPATH"] = os.pathsep.join(filter(None, (str(repo), env.get("PYTHONPATH"))))
return env
def validate_vocab_file(vocab_path: Path, *, kind: str) -> None:
"""Verify a user-provided vocab file is loadable BEFORE copying it into a
run directory. Raises ValueError on failure with a clear, user-facing message.
`kind` is one of {"atom", "bond", "smiles"} — used only in the error message
so the user knows which file is wrong.
"""
if not vocab_path.is_file():
raise FileNotFoundError(f"{kind} vocab file not found: {vocab_path}")
try:
n = count_vocab_entries(vocab_path)
except Exception as exc: # noqa: BLE001
raise ValueError(
f"{kind} vocab file {vocab_path} is not loadable as a KERMT vocab "
f"({type(exc).__name__}: {exc}). Expected a MolVocab JSON or pickle "
f"(or a SMILESVocab pickle for the smiles vocab)."
) from exc
if n <= 0:
raise ValueError(f"{kind} vocab file {vocab_path} contains zero entries")
# ---------------------------------------------------------------------------
# Runner-shared helpers (run.json manifest fields)
# ---------------------------------------------------------------------------
def git_commit_with_env_override(repo: Path) -> tuple[str, bool]:
"""Returns (commit_sha, dirty_tree). Honors `KERMT_REPO_COMMIT` /
`KERMT_REPO_DIRTY` env vars first — set by `scripts/kermt_container.sh`
from the host before launching docker (necessary because `git -C /workspace`
inside the container fails due to bind-mount ownership). Falls back to the
in-container git probe when the env vars aren't set."""
env_commit = os.environ.get("KERMT_REPO_COMMIT")
if env_commit:
env_dirty = os.environ.get("KERMT_REPO_DIRTY", "false").strip().lower() == "true"
return env_commit, env_dirty
try:
sha = subprocess.run(
["git", "-C", str(repo), "rev-parse", "HEAD"],
capture_output=True, text=True, check=True,
).stdout.strip()
diff = subprocess.run(
["git", "-C", str(repo), "status", "--porcelain"],
capture_output=True, text=True, check=True,
)
return sha, bool(diff.stdout.strip())
except Exception:
return "unknown", False
def docker_image_digest(tag: str) -> str | None:
"""Return the docker image's content-addressable Id (sha256:…) for the given
tag, or None if docker isn't available / the image isn't local."""
try:
r = subprocess.run(
["docker", "image", "inspect", tag, "--format", "{{.Id}}"],
capture_output=True, text=True,
)
if r.returncode == 0:
return r.stdout.strip()
except FileNotFoundError:
pass
return None
def format_cmd_replay(argv: list[str], *, env: dict[str, str] | None = None) -> str:
"""Render a copy-pasteable env-prefix + command for the cmd_replay manifest
field. `env` is the set of environment variables to prefix (typically
{CUDA_VISIBLE_DEVICES, WORLD_SIZE})."""
env = env or {}
env_prefix = [f"{k}={shlex.quote(str(v))}" for k, v in env.items()]
quoted = " ".join(shlex.quote(a) for a in argv)
return " ".join(env_prefix + [quoted])
def resolve_single_gpu(override: str | None, *, workflow: str) -> int:
"""Returns a single GPU id (int). The finetune/inference/embed workflows are
single-GPU only; `--gpus '0,1'` or multi-id CUDA_VISIBLE_DEVICES is rejected
with a workflow-specific error. (The pretrain runner has its own multi-GPU
`_detect_gpus` helper — see run_pretrain_local.py.)"""
if override is None:
env_visible = os.environ.get("CUDA_VISIBLE_DEVICES", "").strip()
if env_visible:
ids = [g for g in env_visible.split(",") if g]
if len(ids) > 1:
raise ValueError(
f"CUDA_VISIBLE_DEVICES='{env_visible}' selects multiple GPUs but "
f"the {workflow} workflow is single-GPU only. Restrict to one id."
)
return int(ids[0])
return 0
parts = [p.strip() for p in override.split(",") if p.strip()]
if len(parts) != 1:
raise ValueError(
f"--gpus '{override}' selects {len(parts)} GPUs; the {workflow} workflow is single-GPU only."
)
return int(parts[0])
def assert_prepare_manifest_basics(manifest: dict[str, Any], expected_mode: str) -> None:
"""Standard pre-check for a prepare_data.json before a runner consumes it:
verify `mode` matches and `ok` is True. Raises ValueError with a consistent
error message on either mismatch.
Each runner is responsible for its own required-outputs check after this
(those vary per-mode — e.g. pretrain wants train_dir/val_dir/atom_vocab/
bond_vocab; finetune has the split-method branch; inference/embed want
clean_csv)."""
if manifest.get("mode") != expected_mode:
raise ValueError(
f"prepare_data manifest is mode='{manifest.get('mode')}', expected '{expected_mode}'. "
f"Run `prepare_data.py --mode {expected_mode}` to produce a valid manifest."
)
if not manifest.get("ok"):
raise ValueError(
f"prepare_data manifest reports ok=False: {manifest.get('errors')}"
)
def merge_default_into_applied(
applied: dict[str, dict[str, Any]],
args: argparse.Namespace,
name: str,
defaults_group: dict[str, Any],
) -> None:
"""Standard CLI-override / default-config merge for one hyperparameter.
Mutates `applied` in place:
- If the user passed `--<name>` on the CLI (so `getattr(args, name)` is
not None), records `{"value": cli_val, "source": "user"}`.
- Else if `name` is present in `defaults_group`, records
`{"value": defaults_group[name], "source": "default-config"}`.
- Else `applied[name]` is left absent — the runner's argv-builder skips
the flag, and the downstream argparse default takes effect.
`name` is the snake_case argparse dest (same form used as the dict key);
argparse automatically converts CLI `--<name-with-hyphens>` to that dest,
so `getattr(args, name, None)` is the correct CLI lookup."""
cli_val = getattr(args, name, None)
if cli_val is not None:
applied[name] = {"value": cli_val, "source": "user"}
elif name in defaults_group:
applied[name] = {"value": defaults_group[name], "source": "default-config"}
def run_checkpoint_validator(ckpt: Path, *, mode: str, script_path: Path) -> dict[str, Any]:
"""Invoke `check_checkpoint.py --mode <mode> --ckpt <path>` as a subprocess
and return the parsed JSON. Raises RuntimeError on non-JSON output (e.g. the
validator crashed before printing). `script_path` is the absolute path to
`scripts/check_checkpoint.py` — passed in so this helper has no
dependency on the caller's layout."""
r = subprocess.run(
[sys.executable, str(script_path), "--mode", mode, "--ckpt", str(ckpt)],
capture_output=True, text=True,
)
try:
return json.loads(r.stdout)
except json.JSONDecodeError as exc:
raise RuntimeError(
f"check_checkpoint.py emitted non-JSON output (exit {r.returncode}). "
f"stdout (first 200 chars): {r.stdout[:200]}\n"
f"stderr (first 200 chars): {r.stderr[:200]}"
) from exc
Requirements and compatibility
Written for: Claude Code, OpenAI Codex
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs Python
The author says: Requires docker, nvidia-container-toolkit, and a CUDA-capable NVIDIA GPU. Designed for Claude Code, Codex, and Nemotron.
Security
What our scanner noticed· Medium risk
- Large base64-encoded blobs
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- NVIDIA
- Publisher
- NVIDIA (Official)
- Source
- NVIDIA/skills · skills/bionemo-kermt-continue-pretrain · commit fce3cca
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE-APACHE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by NVIDIA.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download kermt-continue-pretrain.zip