Training and evaluation

Training fine-tunes one of the two released classifiers on annotated or corpus-derived records. Evaluation scores a human spot-check against a model answer key, or compares two model runs on the same corpus.

Data contracts

Training input is JSONL, one record per line, with the task’s canonical text column and an integer label:

Task

Text column

Label

quantum_related

comment

0 (non-quantum) or 1 (quantum-specific)

quantum_category

text

integer 0..``5`` in the category order from Inference

Annotation exports and corpus records are more flexible; use cc4q.train.normalize_training_records() to convert them first.

Training

cc4q.train.normalize_training_records(rows, task)[source]

Convert flexible annotation/corpus rows into canonical training dicts.

Accepts rows with comment / text / comment_text and label fields in label / human_label / quantum_related / quantum_category (including the human_* variants written by the annotation UI). Rows without usable text or a valid label are skipped.

Parameters:
  • rows – Iterable of mappings (annotation exports, corpus records, …).

  • task – "quantum_related" (2 classes) or "quantum_category" (6 classes).

Returns:

A list of {text_col: str, "label": int} records, where text_col is "comment" for Task 1 and "text" for Task 2.

Raises:

ValueError – If task is unknown, or no valid rows remain.

cc4q.train.resolve_base_model(base_model, task)[source]

Resolve model aliases and local caches to a loadable model path.

base_model="released" (or "cc4q-released" / "released-checkpoint") means “warm-start from the released CC4Q classifier for this task”. If that checkpoint is not present locally, the function falls back to bert-base-uncased.

base_model="bert-base-uncased" resolves to the locally cached copy when one was fetched via cc4q download-models --with-base (or baked into the Docker image), so cold-start fine-tuning also works offline; otherwise the Hugging Face id is returned and transformers downloads the weights on first use.

Parameters:
  • base_model – Hugging Face model id/path, or a released alias.

  • task – Axis name whose released checkpoint should be used.

Returns:

A model id/path accepted by transformers.

cc4q.train.train(task, data, output_dir, base_model='bert-base-uncased', batch_size=32, epochs=30, learning_rate=2e-5, max_length=256, test_size=0.2, val_size=0.1, seed=42, max_samples=None, callbacks=None)[source]

Fine-tune one CC4Q classifier.

The input is a JSONL file that already honors the task’s data contract: comment + int label for quantum_related, or text + int label for quantum_category. Use normalize_training_records() to convert annotation/corpus exports first. The data is split into train/validation/test sets; the checkpoint with the best validation F1 is restored before the final test evaluation.

Parameters:
  • task – "quantum_related" (2 classes) or "quantum_category" (6 classes).

  • data – Path to a JSONL training file.

  • output_dir – Directory for the fine-tuned model and tokenizer.

  • base_model – Hugging Face model id/path, or "released" to warm-start from the released checkpoint.

  • batch_size – Per-device train/eval batch size.

  • epochs – Number of training epochs.

  • learning_rate – Optimizer learning rate.

  • max_length – Tokenizer truncation length.

  • test_size – Fraction held out for the final test split.

  • val_size – Fraction of the remaining data used for validation.

  • seed – Random seed for splitting and training.

  • max_samples – Optional cap on the number of training records.

  • callbacks – Optional list of Hugging Face TrainerCallback instances (the Workbench uses this for live progress).

Returns:

A dict with trainer, test_results (eval_* metrics on the test split), output_dir, and train_rows / val_rows / test_rows counts.

Raises:

ValueError – If task is unknown or the data file violates the contract.

Example

from cc4q.train import normalize_training_records, train

rows = [{"comment_text": r["comment_text"],
         "human_label": r["label"]} for r in annotated]
normalized = normalize_training_records(rows, "quantum_related")
# write normalized to JSONL, then:
result = train("quantum_related", "train.jsonl", "out/qr",
               base_model="released", epochs=10)
print(result["test_results"])

Evaluation

cc4q.evaluate.evaluate(human_labels, model_labels)[source]

Compare aligned human and model labels.

Parameters:
  • human_labels – A sequence of labels, or a mapping id -> label.

  • model_labels – A sequence aligned with human_labels, or a mapping id -> label (only shared ids are compared).

Returns:

A dict with n, agreement, kappa, precision, recall, f1, wilson95 ((low, high)), confusion (tp/fp/fn/tn), labels, and the raw pairs. The positive class is "quantum" when present, otherwise the first sorted label. Metrics are nan when undefined.

cc4q.evaluate.evaluate_files(csv_path=None, jsonl_path=None, key_path=None, id_join='no', contaminated=None, human_values=('quantum', 'non-quantum'))[source]

Evaluate a human spot-check export against a model answer key.

The annotation file needs a human label column (human_label by default), a join key (id_join), and optionally repo, comment_type, code_entity_type, and comment_text fields. The key file is JSONL with the same join key and a model_label (or label) field.

Parameters:
  • csv_path – Annotation CSV (preferred when it exists).

  • jsonl_path – Annotation JSONL, used when csv_path is absent.

  • key_path – Model answer-key JSONL. Required.

  • id_join – Column used to join annotations and key (default "no").

  • contaminated – Optional iterable of ids to exclude (for example units that appeared in training data).

  • human_values – Accepted normalized human labels; other rows are counted as skipped.

Returns:

The evaluate() result plus by_repo (per-repository metrics), disagreements, skipped, and excluded counts.

Raises:

ValueError – If key_path or an annotation path is missing, or the key is empty.

cc4q.evaluate.cohen_kappa(pairs)[source]

Compute Cohen’s kappa over aligned label pairs.

Parameters:

pairs – Iterable of (label_a, label_b) pairs.

Returns:

Cohen’s kappa, or nan for no pairs and 1.0 when both raters used a single identical label (expected agreement is 1).

cc4q.evaluate.wilson_ci(k, n, z=1.96)[source]

Wilson score confidence interval for a binomial proportion.

Parameters:
  • k – Number of successes (agreements).

  • n – Number of trials.

  • z – Normal quantile; 1.96 gives a 95% interval.

Returns:

A (low, high) pair. For n == 0 both bounds are nan.

Evaluation output

evaluate() returns n, agreement, kappa, precision, recall, f1, wilson95, confusion (tp / fp / fn / tn), labels, and the raw pairs. evaluate_files() adds the same metrics per repository under by_repo plus a disagreements list and skipped / excluded counts.

from cc4q.evaluate import evaluate_files

result = evaluate_files(
    csv_path="ann/annotations.csv",
    key_path="out/key.jsonl",
    id_join="no",
)
print(f"{100 * result['agreement']:.1f}% "
      f"(95% CI {result['wilson95'][0]:.3f}-{result['wilson95'][1]:.3f})")