CLI API¶
CLI command modules for NAICS Embedder.
This package organizes CLI commands into logical groups: - data: Data generation and preprocessing commands - tools: Utility tools for configuration, epoch health, panel reads, and decisions - training: Model training commands - remote: Verified single-instance training and result transport
Importing this package configures the process for the CLI: it sets PYTORCH_ALLOC_CONF
before torch is loaded and applies the centralized warning filters from
naics_embedder.utils.warnings.
Data Commands¶
CLI commands for NAICS data generation and preprocessing.
This module provides the data command group that orchestrates the data
preparation pipeline. Commands should be run in order or via data all.
Pipeline Stages
- preprocess: Download and clean raw NAICS data files
- supervision: Build one immutable, validated Stage-3 supervision bundle
Commands
roles: Draw the frozen index-entry role table, once; it is committed and preprocess applies
it.
regressor-groups: Draw the regressor panel's held-out four-digit groups, once; they are
committed and the panel reads them.
summaries: Build the window-fitting summaries of over-long channel texts, once per
backbone; they are committed and pinned in code.
preprocess: Download raw NAICS files and produce descriptions parquet.
supervision: Build codebook, pair facts, compatibility distance/relation artifacts,
training pairs, and curriculum thresholds as one versioned bundle.
relations, distances, triplets: Deprecated stage commands; each builds nothing, names
data supervision and exits with status 1.
all: Run the complete data generation pipeline.
all_data()
¶
Run the complete data generation pipeline.
Executes both data preparation stages in order: preprocess, then one complete supervision bundle build. This is the recommended way to prepare data for training from scratch.
Output
data/naics_descriptions.parquet, data/naics_index_roles.parquet,
data/naics_redirections.parquet and a new supervision bundle whose manifest path is
printed.
Example
Run the full pipeline::
$ uv run naics-embedder data all
Note
This command may take 10-30 minutes depending on your system.
Progress is logged to logs/data_all.log.
distances()
¶
Deprecated: builds nothing; data supervision builds the complete bundle.
preprocess(source_dir=None, force=False)
¶
Download and preprocess all raw NAICS data files.
Downloads the official 2022 NAICS taxonomy files from the U.S. Census Bureau and processes them into a unified descriptions parquet file.
The output file contains columns for code, title, description, examples,
and exclusions for each NAICS code at all hierarchy levels (2-6 digit).
Each code's examples channel holds its examples-role index entries only,
per the committed role table (data roles).
Output
data/naics_descriptions.parquet - Unified NAICS taxonomy data.
data/naics_index_roles.parquet - Every index entry with its role.
data/naics_redirections.parquet - Every cross-reference and harvested "Excluded"
paragraph, with the codes it names.
Example
Download and preprocess NAICS data::
$ uv run naics-embedder data preprocess
regressor_groups(codebook, force=False)
¶
Draw the regressor panel's held-out four-digit groups, once.
Holds out a fifth of each sector's four-digit groups (largest remainder, seeded) from the six-digit population Stage 1's finding names. The table is committed, and the regressor panel reads it from then on (roadmap Stage 3).
Output
conf/data/regressor_heldout_groups.csv and
conf/data/regressor_heldout_groups_provenance.json.
Example
Draw the groups over bundle 18403d29's codebook::
$ uv run naics-embedder data regressor-groups --codebook PATH/naics_codebook.parquet
relations()
¶
Deprecated: builds nothing; data supervision builds the complete bundle.
roles(source_dir=None, force=False)
¶
Draw the frozen index-entry role table, once.
Gives every Census index entry exactly one role, per code and stratified: examples-channel text, or a training, validation or test query for the outcome panel (roadmap D4). No validation or test query matches any training text. The table is committed, and preprocess applies it from then on.
Output
conf/data/index_roles.csv and conf/data/index_roles_provenance.json.
Example
Draw the table from local copies of the Census files::
$ uv run naics-embedder data roles --source-dir ~/Downloads/Data
summaries(descriptions='./data/naics_descriptions.parquet', backbone=None, output=WINDOW_SUMMARIES_PATH, force=False)
¶
Build the window-fitting summaries of over-long channel texts, once per backbone.
Every channel text whose marked form is over the backbone's trained window is summarized by
the whole units (sentences, clauses or examples entries) whose pooled vectors best approximate
the text's (roadmap Stage 6b). The backbone is read from the local Hugging Face cache. The
artifact is checked as every reader checks it before it is moved into place; commit it with
the pin this prints, in WINDOW_SUMMARIES (panels/window_summaries.py).
Output
conf/data/window_summaries.csv and conf/data/window_summaries_provenance.json.
Example
Summarize the descriptions bundle 301cce28 was built from::
$ HF_HUB_OFFLINE=1 uv run naics-embedder data summaries
supervision()
¶
Build one immutable, validated Stage-3 supervision bundle.
Computes structural distances (D*) and relations in canonical pair orientation, attaches both directional exclusion flags, and derives the codebook, pair facts, compatibility distance/relation artifacts and matrices, training pairs, and curriculum difficulty thresholds from those facts. The index roles and the redirection table become members, and the manifest records the backbone's input window. Every artifact carries the bundle ID and schema version; the manifest is written only after all artifacts validate, and an existing bundle is never overwritten.
Requires
data/naics_descriptions.parquet, data/naics_index_roles.parquet and
data/naics_redirections.parquet - From the preprocess stage.
The backbone's tokenizer in the local Hugging Face cache - To count each channel's texts
beyond the backbone's trained input window.
Output
data/supervision/stage3-supervision-v2/<bundle-id>/manifest.json and its artifacts.
The manifest path is printed; configure it as supervision.manifest_path.
Example
Build a supervision bundle::
$ uv run naics-embedder data supervision
triplets()
¶
Deprecated: builds nothing; data supervision builds the complete bundle.
Training Commands¶
CLI commands for training NAICS embedding models.
train trains the text stage: Req 11's three terms over the query and code streams, on a code
cache refreshed from the live model, with each epoch read by D6's monitor on the outcome panel's
validation split. That MRR, val/outcome_mrr, keeps the checkpoint, stops the run early and
steps the learning-rate plateau (spec 4.4).
build_datamodule_from_config(cfg, bundle)
¶
Construct the two-stream datamodule of the validated bundle (spec 4.3).
It reads the token cache the export and the reads load (code_token_config), so an arm is
exported from the token rows it trained on, and it draws each epoch's permutations from the
run's seed, data_loader.queries_per_step queries a step.
build_model_from_config(cfg, runtime_contract, bundle, *, run_settings, monitor)
¶
Construct a fresh model under the validated bundle (P15).
The model takes supervision only from the bundle, and every setting from the config: Req 11's
three terms and their two logit scales, the radius bound, and the optimizer's AdamW, warmup
and plateau (spec 4.5). run_settings (utils/training.run_settings) is saved in its
hyperparameters, which the exact-resume guard compares (P19); the monitor reads each epoch
and is not saved.
build_monitor_from_config(cfg, bundle, checkpoint_dir, *, selection_log)
¶
The run's D6 monitor (spec 4.4): the bundle's outcome panel, its reads logged to
selection_log and kept in monitor_reads.jsonl in the run's checkpoint directory.
It tokenizes queries with the token cache's tokenizer and window (code_token_config), as
an arm's reads do. Building it writes nothing: the first read writes the log, and the first
epoch's end the records file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg
|
Config
|
The run's configuration. |
required |
bundle
|
ValidatedSupervisionBundle
|
The validated bundle, whose |
required |
checkpoint_dir
|
Path
|
The run's checkpoint directory. |
required |
selection_log
|
Union[str, Path]
|
|
required |
encoder_architecture_for(cfg)
¶
The configured run's encoder record.
It comes from the same helper the model builds its own record with, so the two cannot drift (spec 4.4).
generate_embeddings_from_checkpoint(checkpoint_path, config, output_path=None, batch_size=32)
¶
Generate hyperbolic embeddings parquet file from a trained checkpoint.
Loads a trained model checkpoint, runs inference on all NAICS codes, and writes the resulting embeddings to a parquet file compatible with HGCN training. HGCN refines Lorentz points, which only the hyperbolic arm has, so a configured flat arm is refused before anything is read (Req 12). The checkpoint must carry the supervision contract of the configured run, the contract of its validated bundle, its geometry included; a checkpoint without one, or with another, is refused before its model loads. One trained under another objective, as every checkpoint saved before Stage 7 was, is refused first, and nothing migrates it (spec 4.5, D2).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
checkpoint_path
|
str
|
Filesystem path to the PyTorch Lightning checkpoint that contains the trained contrastive model weights. |
required |
config
|
Config
|
Project configuration containing data paths used for token caching and parquet loading. |
required |
output_path
|
Optional[str]
|
Optional path for the embeddings parquet. When omitted,
|
None
|
batch_size
|
int
|
Batch size to use during inference to balance throughput and memory usage. |
32
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Filesystem path to the generated embeddings parquet file. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the configured arm is not hyperbolic, or the checkpoint's contract is not the configured run's. |
runtime_contract_for(cfg, bundle)
¶
The checkpoint contract of the configured run, its encoder record and summaries included.
Training's exact resume and the HGCN feeder compare this whole contract with a checkpoint's; export and reads take the encoder record from the checkpoint instead (spec 4.4).
train(config_file='conf/config.yaml', ckpt_path=None, checkpoint_load_mode=CheckpointLoadMode.EXACT, skip_validation=False, overrides=None)
¶
Train the NAICS text encoder: Req 11's three terms, selected on the validation MRR (D6).
Loads the configuration, gates the supervision bundle, and builds the two-stream datamodule,
the outcome monitor (the bundle's panel, logging to conf/data/outcome_panel.yaml's
selection_log, its records in the checkpoint directory) and the model, which records the
run's settings. create_trainer's trainer keeps the earliest epoch with the highest
val/outcome_mrr and last.ckpt, and stops early on the same MRR.
Before anything is built, P19's guards refuse a fresh start into a checkpoint directory that is not empty, and an exact resume from a checkpoint saved in another directory, under other run settings or another seed, or of a run that early stopping ended. Each refusal exits 1. A run that spent its epoch budget without an early stop is not refused: its resume trains nothing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_file
|
Annotated[str, Option(--config, help='Path to base config YAML file')]
|
Path to the base YAML configuration file that describes
data, model, and training settings. Defaults to |
'conf/config.yaml'
|
ckpt_path
|
Annotated[Optional[str], Option(--ckpt - path, help='Path to checkpoint file to resume from, or "last" to auto-detect last checkpoint')]
|
Optional checkpoint path to resume training. Use |
None
|
checkpoint_load_mode
|
Annotated[CheckpointLoadMode, Option(--checkpoint - load - mode, help='exact, the one mode: resume the optimizer, epoch and monitor state (requires a matching supervision contract, checkpoint directory and run settings, and a run early stopping has not ended); nothing migrates weights (D2)')]
|
|
EXACT
|
skip_validation
|
Annotated[bool, Option(--skip - validation, help='Skip advisory pre-flight checks of data files and cache; the supervision bundle gate always runs')]
|
Skip advisory pre-flight checks for data files and tokenization cache. The mandatory supervision bundle gate is never skipped. |
False
|
overrides
|
Annotated[Optional[List[str]], Argument(help="Config overrides (e.g., 'training.learning_rate=1e-4 data_loader.queries_per_step=64')")]
|
Optional list of key-value override strings. Use dot notation
to specify nested config values like |
None
|
Example
Train with default configuration::
$ uv run naics-embedder train
Resume from the last checkpoint, under the settings the run started with::
$ uv run naics-embedder train --ckpt-path last
Train under another learning rate, as a run of its own::
$ uv run naics-embedder train experiment_name=lr-1e-5 training.learning_rate=1e-5
Tools Commands¶
CLI utility commands for configuration, GPU optimization, and metrics analysis.
This module provides the tools command group with utilities for inspecting
configuration, visualizing training metrics, and investigating model behavior.
Commands
config: Display current training configuration. visualize: Plot the durable monitor and epoch health summary. outcome-baseline: Score the lexical stub encoder on the outcome panel's validation split. text-only-table: Embed every code's text with the arm's backbone, frozen (roadmap D9). regressor-panel: Score an arm on the regressor panel's validation or sealed test split. margins: Fix each panel's non-inferiority margin from a reference arm (Req 5). growth-margins: Fix each growth panel's margin from a reference-only read (Req 24). decide: Decide among arms over D8's three panels (Req 5), or among economic candidates against the reference on the two growth panels (Req 24). diagnostics: Report Req 6's structural diagnostics over every codebook code. export-table: Export an arm's code table in Req 2's form, with its provenance (Stage 6). outcome-panel: Score an arm on the outcome panel's validation split (Stage 6). sweep: Read trained seeds on all three validation panels and write an arm record. radius-report: Check radius variation, geometry and loss gradients for a selected checkpoint.
config(config_file='conf/config.yaml')
¶
Display the training configuration a run would use.
Validates the configuration file over the defaults and displays the run's name, seed and inputs, then the settings every run records. A file that sets a key the configuration no longer has is refused (spec 4.5). A missing file, or one the configuration refuses, prints the error and exits 1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_file
|
Annotated[str, Option(--config, help='Path to base config YAML file')]
|
Path to the YAML configuration file to display.
Defaults to |
'conf/config.yaml'
|
Example
Display default configuration::
$ uv run naics-embedder tools config
Display custom configuration::
$ uv run naics-embedder tools config --config conf/custom.yaml
decide_command(arm, margins, name, question, store, output)
¶
Decide among arms under Req 5's rule: over D8's three panels with margins from tools margins, or over the two growth panels (Req 24) with margins from tools growth-margins.
Each A-against-B comparison reads Δ on paired resamples of each panel's units, seeds nested. A is adopted over B when it is non-inferior on every panel (the 95 % interval's lower bound above −δ) and superior on at least one (the 1 − 0.05/n interval above zero: 98⅓ % over three panels, 97.5 % over two). The survivors are the arms no other arm is adopted over, and the tie order picks among them. The record carries the arms with their selection-log records and artifact references, the margins, every comparison, the non-dominated set, the tie order and the chosen arm.
The economic decision reads economic arm records, one or more, and compares each candidate
with the reference covariates+ancestors. Only a candidate adopted over the reference is
eligible for the rule among candidates; with none, the reference stands.
Example
Decide between a candidate and the reference::
$ uv run naics-embedder tools decide --arm candidate.json --arm reference.json \
--margins margins.json --name dimension-8 --question "Is dimension 8 enough?" \
--store ~/naics-artifacts --output decision.json
diagnostics_command(table, geometry, codebook, curvature=1.0, output=None)
¶
Report Req 6's structural diagnostics over every codebook code.
Sector separation (an AUC), within-sector rank correlation (over queries and over sectors), MAP over ancestors, NDCG@5/10/20 with integer lowest-common-ancestor grades, the Pearson correlation of distance with D*, and parent retrieval@1/5 without the 522 unary pairs. The report describes an arm: nothing selects on it, and no statistic in it has a threshold.
--geometry must be the table's own arm: a table whose export provenance names another
geometry is refused, and so is one whose provenance file exists but cannot be read as JSON.
A table with no provenance file, or whose provenance names no geometry, is read as given.
Example
Report on a hyperbolic arm's export::
$ uv run naics-embedder tools diagnostics --table arm.parquet --geometry hyperbolic \
--codebook PATH/naics_codebook.parquet
export_table(checkpoint, output, config_file='conf/config.yaml', overrides=None)
¶
Export an arm's code table in Req 2's form, with its provenance (roadmap Stage 6).
Every code goes through the checkpoint's model in eval mode. The table holds code,
index, level and e0 … e{d-1}: each code's tangent vector at the origin, in the
bundle's codebook order. The checkpoint's supervision contract must match the configured
bundle. Its encoder record is its own, so a d = 8 checkpoint exports under a d = 16 config.
Example
Export a run's selected checkpoint::
$ uv run naics-embedder tools export-table \
--checkpoint checkpoints/reference/epoch=001.ckpt \
--output data/reference/arm_table.parquet supervision.manifest_path=PATH
growth_margins_command(codebook, name, store, output, purpose=None, log=None, lock=LOCK_FILE)
¶
Read the reference alone on both growth panels and fix each one's margin δ (Req 24).
The read scores, on each growth regime's level-6 validation split, only the comparators that
read no candidate: the covariates, one-hot (seen regime only) and ancestor indicators, each
alone and with the covariates. δ is the decision config's relative_margin r (0.05, U13)
times the MSE of the reference covariates+ancestors there. The panel reads growth
whatever the regressor config's outcome says; it stays level for tools
regressor-panel and tools sweep.
Fix the margins once, before any candidate is read on growth: a decision refuses a candidate
read before its margins were fixed. The record names the platform, Python and uv.lock
the read ran under, and every candidate read must run there too, since a decision pairs only
bit-identical reference predictions.
Example
Fix the growth margins::
$ uv run naics-embedder tools growth-margins --codebook PATH/naics_codebook.parquet \
--name growth-margins --store ~/naics-artifacts --output growth_margins.json
margins_command(reference, multiple, name, store, output)
¶
Fix each panel's non-inferiority margin δ from a reference arm (Req 5).
δ is the multiple times the reference arm's across-seed standard deviation of the panel's decision statistic (D10). Fix the margins before any other arm of a decision reads a panel: a decision refuses every run that read before its margins were fixed.
Example
Fix the margins at half a standard deviation::
$ uv run naics-embedder tools margins --reference reference.json --multiple 0.5 \
--name reference-margins --store ~/naics-artifacts --output margins.json
outcome_baseline(purpose='lexical baseline on the validation split', index_roles=None, descriptions=None, log=None, output=None)
¶
Score the training-free lexical encoder on the outcome panel's validation split.
Decodes every validation query to the nearest six-digit code by hashed character trigrams under cosine distance, and reports top-1 accuracy, MRR, Hit@1/5/10 and the level of the lowest common ancestor. The read is logged in the selection log. The test split stays sealed: this command never opens it.
Example
Score the baseline on the preprocessing outputs::
$ uv run naics-embedder tools outcome-baseline
outcome_panel(checkpoint, table, purpose, config_file='conf/config.yaml', log=None, output=None, overrides=None)
¶
Score an arm on the outcome panel's validation split under its own distance (Stage 6).
Queries go through the checkpoint's model; codes are decoded from the table exported from it.
The read is logged with the table's matrix_fingerprint and the checkpoint's SHA-256. The
test split stays sealed: this command never opens it.
Example
Read the validation split for an exported table::
$ uv run naics-embedder tools outcome-panel \
--checkpoint checkpoints/reference/epoch=001.ckpt \
--table data/reference/arm_table.parquet --purpose 'selected checkpoint validation' \
supervision.manifest_path=PATH
radius_report_command(checkpoint, table, output=None, config_file='conf/config.yaml', overrides=None)
¶
Check radius variation, geometry and loss gradients for one selected checkpoint.
Gradients use epoch 0, step 0 of the saved seed and saved query chunk size. The checkpoint
and its table must share an export provenance. The radius checks are the hyperbolic arm's: a
flat arm (Req 12) has no radial term or live-radius head, so its report checks its terms and
scales alone and records radius as null. The report names the arm's geometry and is
written even when a measured criterion fails; a failure exits 1. No evaluation split is
scored.
regressor_panel(coordinates, text_only, codebook, regime=None, level=None, split=VALIDATION, purpose=None, open_purpose=None, reopen_reason=None, log=None, output=None)
¶
Score an arm on the regressor panel: out-of-sample predictions per row (roadmap Stage 3).
Every Req 2 comparator is fitted by ridge on standardized features, the penalty tuned inside the remainder. The validation split reads only the remainder; the test split opens each regime's sealed outer set first, and both the opening and the read are logged.
It reads level mode only. Every read scores the arm and the text-only table, and Req 24
records the economic margin before any candidate's growth error exists, so a config whose
outcome is growth is refused before anything is read.
Example
Score an arm's table on the validation split of both regimes at six digits::
$ uv run naics-embedder tools regressor-panel --coordinates arm.parquet \
--text-only text_only.parquet --codebook PATH/naics_codebook.parquet
sweep_command(runs, seed, text_only, store, output, purpose, name='reference', accelerator='cuda', log=None, config_file='conf/config.yaml', overrides=None)
¶
Read each trained seed once on all three validation panels and save its arm record.
Every seed's checkpoints and monitor reads are checked before the first decision read. The
record carries the monitor reads that selected each checkpoint. --accelerator describes
training; the export and decision reads use this machine's device.
It reads the regressor panel in level mode only (D8): a regressor panel config whose
outcome is growth is refused before any seed is checked or read (Req 24).
text_only_table(descriptions, output, backbone=None)
¶
Embed every code's text with the arm's backbone, frozen (roadmap D9).
Each of the four channels is mean-pooled over its tokens, and a code's vector is the mean of its present channels. The backbone is read from the local Hugging Face cache. The regressor panel reduces the table to the arm's dimension by PCA.
Output
The table, and <stem>_provenance.json beside it.
Example
Embed the text bundle 18403d29 was built from::
$ uv run naics-embedder tools text-only-table \
--descriptions data/naics_descriptions.parquet --output /tmp/text_only.parquet
visualize(summary, output_dir=None)
¶
Plot the run's monitor MRR, loss means, logit scales and radius mean and SD per level.
Read epoch_summary.jsonl beside the run's checkpoints. The figure is epoch_metrics.png
in --output-dir, or visualizations beside the summary by default.