Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions template/AGENTS.md.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ for material unresolved choices; exploratory assumptions require explicit opt-in
- Intermediate payloads are opaque. Generic tests validate their envelopes, not their contents.
- MEDS-DEV owns dataset-specific predicates; the algorithm owns their interpretation.
- Never associate outputs with prediction keys by row order.
- Long-running steps stream progress through `logging` (phases with planned sizes, step/epoch out of total,
training and tuning loss, kept checkpoint, inference counts; see "Progress logging" in the guide). Log only
aggregates and configuration: never subject IDs, times, codes, values, labels, predictions or sample rows.
- Keep `STUB_PROFILES = set(PROFILES)` until every registered command and the real end-to-end adapter work.
- Replace the intentional failure in `tests/test_primary_behavior.py`. Prove that a known signal reaches
the algorithm's real selected codes/features and produces the expected behavior, with a shuffled-label
Expand Down
27 changes: 27 additions & 0 deletions template/docs/IMPLEMENTATION_GUIDE.md.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,33 @@ dependencies and persisted fitted state. Avoid speculative abstractions, mutable
hidden singletons, import-time computation and duplicated core behavior. Use the same runner from the
CLI and `tests/e2e.py`; demonstrate independent execution after reopening serialized inputs.

### Progress logging

Steps that can run for minutes or more must report progress while they run, so a long job can be told apart
from a hung one from its log alone. Use `logging.getLogger(__name__)` and never `print` for progress: the
generated CLI configures logging to stderr with one flushed line per record (level from `LOG_LEVEL`,
default `INFO`), and core streams each step's output into `logs/<step>.log` and, under SLURM, the job's
output files as it is written. Log from the algorithm, including from loops in long-running dependencies
(through their own callbacks or logging, configured to the same stream).

Log at least:

- each phase as it starts, with its planned size (for example `stage 2: context 16384, 1015 optimizer steps`)
and its elapsed time when it ends;
- for iterative training, every epoch or every N optimizer steps (bounded, e.g. at most a line a minute at
steady state): step or epoch out of the total, training loss, learning rate, elapsed time and throughput;
- every tuning evaluation (tuning loss or metric), early-stopping decisions and which checkpoint is kept;
- for inference and generation, items done out of the total (subjects, prediction times, samples) with rate.

Logs must never reveal patient-level data. Log only aggregates over many subjects and configuration values:
counts, sizes, timings, losses and metrics computed over a split or a batch, vocabulary size, resource use.
Never log subject IDs, prediction times, dates, event or code sequences, individual values, labels or
predictions of a subject, generated trajectories, sample rows of any table, or the free text of codes and
values; never log a batch's contents, and avoid exceptions whose message embeds such values (catch and
re-raise with an aggregate message). Do not log code names or vocabulary entries either: a rare code can
identify a patient in a small cohort. Paths, digests and configuration are fine. Logs are copied off
clusters and into CI output, so treat them as shareable.

### Public API and internal helpers

Expose the named algorithm and configuration classes for callers. Give implementation-only classes,
Expand Down
17 changes: 17 additions & 0 deletions template/src/{{ algorithm_slug }}/__main__.py.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import argparse
import json
import logging
import os
import sys
from pathlib import Path

Expand All @@ -18,6 +20,20 @@ def _value(text: str):
return text


def _configure_logging() -> None:
"""Stream step progress to stderr, one flushed line per record, so it reaches the step log while running.

Core sends a step's stdout and stderr to ``logs/<step>.log`` (and, under SLURM, the job's output files) as they
are written. Python block-buffers ``print`` to a file, whereas a logging handler flushes every record.
``LOG_LEVEL`` (default ``INFO``) sets the level. An existing configuration is kept.
"""
logging.basicConfig(
level=os.environ.get("LOG_LEVEL", "INFO").upper(),
stream=sys.stderr,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)


def main() -> None:
repository = create_repository()
if len(sys.argv) > 1 and sys.argv[1] == "run":
Expand Down Expand Up @@ -56,6 +72,7 @@ def main() -> None:
if not key or key in arguments:
parser.error(f"Empty or duplicate argument {key!r}")
arguments[key] = _value(value)
_configure_logging()
repository.run(args.command, arguments, profile=profile)
except (ValueError, TypeError, FileNotFoundError) as error:
parser.error(str(error))
Expand Down
5 changes: 5 additions & 0 deletions tests/test_typed_execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,10 @@ def preprocess_data(self, request):
return PayloadMetadata("fixture-data")

def train_supervised(self, request):
import logging

outcomes = request.labels.read()["boolean_value"]
logging.getLogger(__name__).info("fitting on %d labels", len(outcomes))
alpha = self.config.smoothing
probability = (outcomes.sum() + alpha) / (len(outcomes) + 2 * alpha)
(request.output.directory / "probability.txt").write_text(str(probability))
Expand Down Expand Up @@ -103,6 +106,8 @@ def run(step, **arguments):
output_supervised_algorithm_dir=algorithm,
)
assert result.returncode == 0, result.stderr
# The generated CLI configures logging, so a step's progress records reach its output.
assert f"INFO {slug}.{slug}: fitting on 3 labels" in result.stderr
args = {
"input_data_dir": data,
"input_supervised_algorithm_dir": algorithm,
Expand Down
Loading