Skip to content

Evaluation Engine API

The engine builds components from a YAML plan and executes the shared evaluation workflow. Start with the evaluation guide for commands, configuration, and result files. The sections below document the data contracts and supporting APIs used by method integrations.

Data Contracts

cofai.engine.schema

Unified eval data structures (protocol implementation).

This module is the engine-level home for eval contracts.

EvalBatch dataclass

EvalBatch(inputs: Dict[str, Any], samples: List[Dict[str, Any]] = list())

Packed batch ready for model inference (MMEngine-style split).

Produced by collate+pack logic (typically in cofai.engine.dataloader).

  • inputs: shared model inputs; currently contains img as FloatTensor[B,C,H,W] for every image task.
  • samples: length B; each entry matches the dataset/transform dict except img is omitted. Task-specific inputs and annotations live under their task kind (for example samples[i]["vqa"]).

StepOutput dataclass

StepOutput(timing: Dict[str, float] = dict(), bits: Dict[str, float] = dict(), pred: Dict[str, Any] = dict(), gt: Dict[str, Any] = dict(), per_sample_records: List[Dict[str, Any]] = list(), artifacts: Dict[str, Any] = dict())

Model step output consumed by evaluators and output writers.

Component Registry

cofai.engine.registry

Registry and dynamic class instantiation for the engine layer.

Resolution order for get_obj_from_str:

  1. Fully-qualified name: "package.module.Class" via importlib (sys.modules first).
  2. Short name: global registry (classes registered with @register("Name")).
  3. Short name fallback: scan common cofai modules (legacy builder behavior).

Notes:

  • No wildcard imports; no implicit module scanning for FQDNs.
  • Prefer fully-qualified names in configs for clarity.

Registry

Registry()

Simple name -> class registry.

get

get(name: str) -> Optional[Type]

Return the class by name, or None if not found.

list_registered

list_registered() -> list

Return a list of all registered names.

register

register(name: str) -> Callable[[Type], Type]

Decorator to register a class under the given name.

get_obj_from_str

get_obj_from_str(string: str, reload: bool = False) -> Type

Resolve a class object from string.

Supported formats:

  1. Fully-qualified: "package.module.Class" (preferred).
  2. Short name: resolved from the global registry, then from a fixed list of cofai modules.

instantiate_class

instantiate_class(config: Dict[str, Any], **kwargs) -> Any

Instantiate a class from a config dict with key type.

instantiate_transforms

instantiate_transforms(config: Dict[str, Any], **kwargs) -> Any

Instantiate a transform pipeline; optional nested transforms list.

list_registered_classes

list_registered_classes() -> list

List all names currently registered in the global registry.

register

register(name: str) -> Callable[[Type], Type]

Decorator to register a class in the global registry.

Configuration

cofai.engine.config

Component Builders

cofai.engine.builder

build_transforms

build_transforms(transforms_cfg: Any)

Build eval-time transforms from a list of config dicts.

Batch Preparation

cofai.engine.dataloader

Build DataLoader that yields EvalBatch.

build_dataloader

build_dataloader(cfg: Any, dataset: Any) -> DataLoader

Return DataLoader producing EvalBatch.

collate_fn

collate_fn(batch: List[Dict[str, Any]]) -> EvalBatch

Stack the shared image input and preserve per-task sample payloads.

Evaluation

cofai.engine.evaluator

Multi-task metric evaluation for unified eval pipeline.

MultiTaskEvaluator

MultiTaskEvaluator(task_configs: List[TaskConfig])

Multi-task meter aggregator (meters only).

TaskConfig dataclass

TaskConfig(label: str, meter: Meter)

Per-task meter definition for unified eval.

eval_model MUST produce StepOutput.pred/gt for this label in final form.

TaskSpec dataclass

TaskSpec(label: str, kind: Optional[str] = None, params: Optional[Dict[str, Any]] = None)

Task semantics for one task label.

kind is optional; when present it should come from ALLOWED_KINDS.

infer_kind

infer_kind(*, label: str, kind: Any) -> Optional[str]

Infer kind from config.

Evaluation Entry Points

cofai.engine.run_eval

Eval-time inference and default DataUnitCodec test-step helpers.

Entry: @hydra.main with config_path = repo conf/ (standard Hydra CLI, e.g. --config-name=plan/<file>).

Current limitation: the eval path is only maintained for batch size = 1. Multi-sample batches are not part of the supported contract.

eval_step

eval_step(*, model: Any, batch: EvalBatch, step_ctx: Optional[Dict[str, Any]] = None) -> StepOutput

Default test_step for DataUnitCodec-style models.

Required runtime context is read from ctx (passed by Runner/TestLoop): - cfg, tasks, device, task_specs

finalize_results

finalize_results(*, records: List[Dict[str, Any]], evaluator: MultiTaskEvaluator) -> Dict[str, Any]

Merge per-sample record means and task metrics into one flat dict for result.json.

Order: timing / bpp aggregates first, then task-level meter metrics (e.g. cls_top-*).

inference_model

inference_model(model: Any, x: Any, *, qp: Any = 1, real: bool = False, tasks: List[str] | None = None, task_specs: Any | None = None, profile: bool = False, task_data: Optional[Dict[str, Any]] = None) -> Tuple[Dict[str, float], Dict[str, float], Dict[str, Any]]

Single inference helper used by unified eval.

When profile is True, the codec-only encode/decode times recorded by the model (model._codec_time) are merged into the returned timing dict.

main

main() -> None

Package entrypoint: python -m cofai.engine.run_eval.

measure_codec_complexity

measure_codec_complexity(*, loader: Any, model: Any, device: Any, qp: Any, max_samples: int | None) -> Dict[str, Any]

Average latent-codec params/FLOPs over the dataset (profile pass).

Runs before the eval loop so the codec is measured on clean (non inference-mode) state. codec_params is constant; the *_flops fields are averaged over samples (they vary with input resolution).

multi_run

multi_run(cfg: Any)

Each cfg.multi_run key → one run_eval; aggregate summary.json.

run_eval

run_eval(cfg: Any, *, write_subdir: Optional[str] = None, result_quality: Optional[str] = None) -> tuple[Dict[str, Any], List[Dict[str, Any]]]

Unified eval entrypoint (engine-level).

write_subdir: when set, write result.json / config.yaml directly under this directory (used by multi_run per-quality folders). Otherwise use logs/<plan.name>/.

task_decode_pred

task_decode_pred(raw: Any, task: str) -> Any

Decode per-task raw outputs into pred-ready tensors/arrays.

write_eval_outputs

write_eval_outputs(output_dir: str, *, name: str, description: str, results: Dict[str, Any], quality: Optional[str] = None, records: Optional[List[Dict[str, Any]]] = None, cfg: Any | None = None) -> str

Write result.json and return its path.

Runtime Controls

cofai.engine.runtime

Runtime noise controls for eval entrypoints.

suppress_unnecessary_runtime_output

suppress_unnecessary_runtime_output(*, verbose: bool = False) -> None

Suppress noisy third-party logging/warnings during eval.

This is the only public entrypoint expected by eval callers. The exact warning filters, environment defaults, and library-specific logger settings are runtime policy details kept inside this module.

Bitrate Accounting

cofai.engine.bitrate

Bit accounting for coded units emitted by CoFAI models and codecs.

bits_from_coded_data

bits_from_coded_data(out: dict[str, Any]) -> dict[str, float]

Flatten per-stream bits from any coded-data container.

bits_from_coded_unit

bits_from_coded_unit(data: dict[str, Any]) -> dict[str, float]

Return per-stream bits from one real or estimated coded unit.

Checkpoint Loading

cofai.engine.checkpoint

load_checkpoint_into_model

load_checkpoint_into_model(model: Module, load_cfg: Any) -> None

Load a checkpoint into model using a flexible config dict.

Recommended config location: plan.load (engine-level). Supported fields: - path (str, required) - strict (bool, default false) - rules (list[[type, pattern, replacement]], optional) # rename_key_by_rules - state_dict_key (str, default "state_dict") - weights_only (bool, default true) - map_location (str, default "cpu")