📙 How-to Guide · task-oriented
Model Testing and Test Data Processing¶
Overview¶
DynVision separates model evaluation into two coordinated steps:
- Running the
test_modelworkflow rule to produce raw classifier predictions and layer responses. - Aggregating those artifacts with
process_test_data.pyto build analysis-ready tables.
This guide explains how to configure each phase, what files are created, and how to customize metrics for downstream visualization.
Prerequisites¶
- A trained model checkpoint generated with the
train_modelrule. - Test data prepared under
project_paths.data.interim. - A populated experiment entry in
dynvision/configs/config_experiments.yaml(defines loaders, parameters, and data arguments). - Snakemake environment configured as described in the project README.
Workflow Summary¶
| Stage | Snakemake rule | Key script | Outputs |
|---|---|---|---|
| Evaluation | test_model (from workflow/snake_runtime.smk) |
SCRIPTS/runtime/test_model.py |
test_outputs.csv, test_responses.pt per experiment slice |
| Processing | process_test_data (from workflow/snake_visualizations.smk) |
SCRIPTS/visualization/process_test_data.py |
Consolidated test_data.csv with metrics |
Step 1: Configure the Experiment¶
Each experiment in config_experiments.yaml specifies:
parameter: the primary sweep variable injected into filenames.data_loader: class responsible for assembling stimuli.data_args: mapping of loader arguments; values may be scalars or lists to expand across combinations.- Optional
statusentries (e.g.,trained-epoch=99) to select intermediate checkpoints.
Example excerpt:
duration:
status: trained
parameter: stim
data_loader: StimulusDuration
data_args:
dsteps: 30
intro: 1
stim: [1, 3, 5, 10, 20]
idle: 20
data_args and status to enumerate concrete runs. Category lists in experiment_config.categories (e.g., rctype, trc) provide wildcard values for comparisons.
Extending Experiment Types¶
To introduce a novel stimulus protocol:
- Implement a DataLoader subclass in
dynvision/data/dataloader.py(useStandardDataLoaderor the temporal loaders as templates). Provide aliases via@alias_kwargsso configuration keys (for examplestim,intro) map cleanly onto constructor arguments. - Register the class name in the
DATALOADER_CLASSESdictionary soget_data_loadercan resolve it during workflow execution. - Reference the new loader in
config_experiments.yamlby settingdata_loaderand supplying the requireddata_args. Snakemake will automatically expand the experiment combinations and pass them into thetest_modelrule.
Step 2: Run the test_model Rule¶
From dynvision/workflow/ execute:
- Loads the trained weights from
project_paths.models/{model_name}. - Mounts the test dataset symlink specified by
data_loaderanddata_group. - Calls
SCRIPTS/runtime/test_model.pywith batch size, normalization stats, and anymodel_args/data_argssupplied via configuration. - Emits two artifacts under
project_paths.reports/{data_loader}/<formatted-run-id>/: test_outputs.csv: per-sample classifier predictions, labels, confidences, and metadata.test_responses.pt: serialized tensor dictionary with layer responses (includingclassifierlogits when requested).
Step 3: Inspect Intermediate Results¶
Before aggregation, verify the evaluation pass:
test_outputs.csvcolumns includesample_index,times_index,label_index,guess_index, and other task-specific fields produced by the runtime script.test_responses.ptshould contain layer tensors keyed by module name. Missing tensors usually indicate disabled logging in the model configuration.
Step 4: Process Test Data¶
The visualization workflow calls process_test_data.py via the process_test_data rule:
snakemake process_test_data \
--config experiment=duration model_name=DyRCNNx4 data_name=cifar100 seed=0 category=rctype
--responses/--test_outputs: glob-expanded lists of matching.ptand.csvfiles.--parameter: experiment-level sweep key (e.g.,stim).--category: comparison axis taken fromexperiment_config['categories'].--additional_parameters: optional metadata to extract from directory names (defaultepoch).--measures: metrics to compute (layer statistics, confidence scores, top-k accuracy, classifier unit activations).--sample_resolution: choosesample(per image) orclass(aggregated byfirst_label_index).--remove_input_responses: remove.ptresponses after successful processing to save space.
Script Responsibilities¶
Inside process_test_data.py:
- Validates metadata consistency between
.ptand.csvfilenames usingextract_param_from_string. - Loads the CSV with
load_dfand augments it viaprocess_test_performance, addingfirst_label_indexandaccuracyindicators. - Optionally computes classifier-derived metrics (confidence, top-k accuracy, top-N unit activations) when
test_responses.ptcontains aclassifiertensor. - Streams layer responses through
process_layer_responses_incrementalto assemble large-scale statistics without exhausting memory. - Attaches requested metadata columns (primary parameter, category, additional parameters) for downstream plotting.
- Writes a unified
test_data.csvper batch; Snakemake concatenates batches into the final report path underproject_paths.reports/{experiment}/.
Custom Invocation¶
You can call the script directly, for example:
python dynvision/processing/process_test_data.py \
--responses path/to/test_responses.pt \
--test_outputs path/to/test_outputs.csv \
--output reports/duration/run_01/test_data.csv \
--parameter stim \
--category rctype \
--measures response_avg response_std accuracy_top3 \
--additional_parameters epoch tau \
--sample_resolution sample \
--fail_on_missing_inputs False
--fail_on_missing_inputs False to skip missing file pairs without aborting the run—helpful when partial evaluations finish.
Step 5: Utilize the Processed Dataset¶
Downstream visualization rules (e.g., plot_performance, plot_responses) consume the test_data.csv files produced above. Each CSV contains:
- Metadata columns (experiment parameter, category, additional parameters).
- Temporal indices (
times_index) and presentation identifiers (first_label_index). - Layer statistics (
response_avg,response_std, etc.). - Performance measures (
accuracy,accuracy_topK, confidence metrics). - Optional classifier activation columns (
classifier_topN,_id).
Metadata and Index Columns¶
- Index columns:
sample_indextracks individual images whensampleresolution is selected;times_indexmarks timestep positions;first_label_indexrecords the earliest valid class per sample (used for grouping and presentation-level aggregation). - Parameter column: named after the experiment’s
parameterentry (e.g.,stim,contrast) and repeats the sweep value extracted from the file path. - Category column: matches the Snakemake wildcard specified in the workflow invocation (e.g.,
rctype,trc), enabling comparisons across architectural variants. - Additional parameters: any names supplied via
--additional_parametersare extracted from response directories and inserted verbatim, allowing downstream filters likeepoch == 99ortau == "5".
Available Measure Columns¶
process_test_data.py and process_single_test.py organize measures into four categories:
- Layer metrics (
response_avg,response_std,spatial_variance,feature_variance): computed per layer and timestep from response tensors. When--sample_resolution sampleis used, they emit columns such as{layer_name}_response_avg. Underclassresolution the same metrics aggregate over presentations (first_label_index). - Confidence metrics (
guess_confidence,label_confidence,first_label_confidence): derived from classifier logits. Values reflect softmax probabilities and remain at the same resolution as the CSV input. - Top-k accuracy metrics (
accuracy_top3,accuracy_top5, etc.): Boolean indicators per timestep showing whether the ground-truth label appears in the model’s top-k predictions. With class resolution, they are averaged and accompanied by standard deviation columns. - Classifier activations (
classifier_topN,classifier_topN_id): capture the activation magnitude and corresponding unit index for the most active classifier channels, useful for feature analysis.
Column Naming Conventions¶
- Scalar columns retain their measure name (e.g.,
accuracy,label_confidence). - Layer metrics follow
{layer}_{measure}for sample resolution; class resolution introduces_avgand_stdsuffixes when values vary within a presentation. - Additional parameters requested via
--additional_parametersappear as plain columns (e.g.,epoch,tau). - When resolution is
class,sample_indexis removed and summary columns are keyed byfirst_label_indexandtimes_index.
These tables can also be loaded manually into analysis notebooks:
import pandas as pd
test_data = pd.read_csv("logs/reports/duration/duration_DyRCNNx4:.../test_data.csv")
filtered = test_data.query("first_label_index == 5 and times_index <= 10")
Common Issues and Solutions¶
- Mismatched metadata: The processor raises
ValueErrorif filename parameters disagree between.ptand.csv. Confirm Snakemake wildcards produce aligned paths. - Missing classifier tensor: Confidence metrics require
responses["classifier"]. Enable classifier logging in the model or remove those measures. - Memory warnings: Lower
--batch_sizeor adjust--memory_limit_gbwhen processing very large response sets. - Empty outputs: Ensure
test_outputs.csvcontains rows for every sample; reruntest_modelif the evaluation terminated early.
Related Resources¶
- Training for training models and generating checkpoints.
docs/development/guides/ai-style-guide.mdfor workflow conventions.docs/reference/workflow-overview.md(if available) for a schematic of Snakemake rules.- Source scripts in
dynvision/runtime/test_model.pyanddynvision/processing/process_test_data.pyfor implementation details.