Skip to content
Open
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
13 changes: 8 additions & 5 deletions docs/api/datasets.rst
Original file line number Diff line number Diff line change
Expand Up @@ -51,18 +51,21 @@ Task caches and when to clear them
directory, in two layers:

- ``tasks/<task_name>_<hash>/task_df.ld`` holds the raw samples the task
returned. The hash covers the task's attributes (its constructor arguments
and anything else set on ``self``) and its ``input_schema`` and
``output_schema``.
returned. The hash covers the task's attributes (what its constructor leaves
on ``self``, and public class attributes), its ``input_schema`` and
``output_schema``, and its ``version`` (see :doc:`tasks`).
- ``samples_<hash>.ld`` inside it holds the processed samples. This hash also
covers any processors you passed in, the split (with ``set_task(split=...)``)
and the storage format.

So changing a task argument, a schema, the processors or the split gives a new
cache automatically. **Editing the task's code does not**: the hash does not see
the body of ``__call__``. Neither does upgrading PyHealth to a version whose
task or processor code changed. In those cases the old samples are reused
without a warning. Clear the cache to rebuild them:
task or processor code changed, unless the task's ``version`` changed too. In

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in c0234ba. The page now says that functions stored on a task are the exception: their code is part of the hash, so editing one, in user code or in PyHealth, gives a new cache.

those cases the old samples are reused without a warning. Functions stored on
the task are the exception: their code is part of the hash, so editing one, in
your code or in PyHealth, gives a new cache. Bump the task's
``version``, or clear the cache to rebuild them:

.. code-block:: python

Expand Down
64 changes: 63 additions & 1 deletion docs/api/tasks.rst
Original file line number Diff line number Diff line change
Expand Up @@ -185,12 +185,73 @@ supports ``len()`` and index access, ready for a DataLoader.

If you re-run ``set_task()`` with the same task and processor configuration,
PyHealth detects the existing cache and skips reprocessing. The cache key holds
the task's arguments and schemas but not its code, so after you edit a task's
the task's configuration and schemas but not its code, so after you edit a task's
``__call__``, run ``dataset.clear_task_cache(task)`` (see *Task caches and when
to clear them* in :doc:`datasets`). During
development it is useful to set ``dev=True`` on the dataset, which limits
processing to 1 000 patients so iterations are fast.

What counts as the same configuration?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Each task configuration gets its own cache directory, named after a
fingerprint of everything that determines the generated samples:

- the state your task's ``__init__`` leaves on the instance, rather than the
arguments as passed -- ``MyTask()`` and
``MyTask(window=timedelta(days=15))`` share a cache when 15 days is the
default, and so do two spellings that ``__init__`` normalises to the same
value;
- public, non-callable class-level attributes, the input schema and the output
schema;
- ``BaseTask.version`` (see below).

Attributes that do not affect the output are ignored, so changing
``num_workers`` reuses the cache. Add your own via ``fingerprint_exclude``::

class MyTask(BaseTask):
fingerprint_exclude = frozenset({"debug_dir"})

The fingerprint is a digest, so the directory name alone does not tell you
which parameter changed. Each cache directory therefore contains a
``task_meta.json`` recording the full configuration in readable form, and
``set_task()`` logs its path at INFO level. The file holds the task's
attributes as they are, strings included: exclude an attribute that should not
be written to a shared cache, such as a credential, with ``fingerprint_exclude``.

.. warning::

**Editing** ``__call__`` **does not invalidate the cache.** The fingerprint
covers configuration, not code, so changing your labelling logic without
changing any argument will silently reuse the samples built by the previous
version. Bump ``version`` on the task when its logic changes::

class MyTask(BaseTask):
version = "2" # was "1"; excluded ICU stays under 24h

Alternatively, set ``PYHEALTH_FINGERPRINT_SOURCE=1`` before importing
PyHealth to fold a structural hash of ``__call__`` and ``pre_filter`` into
the fingerprint. Comments, whitespace and docstrings do not count, but
renaming a local variable does, and helpers that ``__call__`` calls are not
covered, so this is off by default.

If a task attribute cannot be fingerprinted deterministically (an object
whose ``repr()`` embeds a memory address, an iterator, a sparse tensor, or a
function whose source cannot be read, such as one made by ``exec()``),
``set_task()`` raises ``UnfingerprintableError`` rather than risk a colliding
or unstable cache key. This is the default, and a change: such tasks used to
get a key that differed on every run, or that two configurations could share.
Give the class a ``__pyhealth_fingerprint__()`` method returning a plain
description of its configuration, or exclude the attribute. To get a warning
and a best-effort key instead of an error, set
``PYHEALTH_FINGERPRINT_STRICT=0`` before importing PyHealth.

A function or bound method is identified by its code and by what it carries:
captured variables, default values and the object it is bound to. Tables
(pandas, polars) are identified by their labels, dtypes and values. The
fingerprint does not follow module-level globals read by a function or the
contents of a file behind a path.

.. note::

**A note on multiprocessing.** ``set_task()`` can spawn worker processes
Expand All @@ -213,6 +274,7 @@ Available Tasks
:maxdepth: 3

Base Task <tasks/pyhealth.tasks.BaseTask>
Task Fingerprint <tasks/pyhealth.tasks.fingerprint>
Task Card <tasks/pyhealth.tasks.TaskCard>
In-Hospital Mortality (MIMIC-IV) <tasks/pyhealth.tasks.InHospitalMortalityMIMIC4>
In-Hospital Mortality (MEDS) <tasks/pyhealth.tasks.InHospitalMortalityMEDS>
Expand Down
12 changes: 12 additions & 0 deletions docs/api/tasks/pyhealth.tasks.fingerprint.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
pyhealth.tasks.fingerprint
=======================================

Deterministic cache keys for ``set_task``. Replaces the previous
``json.dumps(..., default=str)`` hash, which was neither stable across
processes nor injective for large arrays.

.. automodule:: pyhealth.tasks.fingerprint
:members: UnfingerprintableError, task_spec, task_fingerprint, task_cache_name, processors_fingerprint, write_task_metadata, slugify
:undoc-members:
:show-inheritance:
:exclude-members: Any, Mapping, Path, PurePath
24 changes: 24 additions & 0 deletions examples/task_fingerprint.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""Show that task cache keys include the task's effective configuration (#916).

Two ReadmissionPredictionMIMIC3 configurations that differ only by
``window`` must produce different cache directory names. A slash in
``task_name`` (as used by BenchmarkEHRShot) is slugified to a single
path component.
"""

from datetime import timedelta

from pyhealth.tasks.benchmark_ehrshot import BenchmarkEHRShot
from pyhealth.tasks.fingerprint import task_cache_name, task_fingerprint
from pyhealth.tasks.readmission_prediction import ReadmissionPredictionMIMIC3

if __name__ == "__main__":
t15 = ReadmissionPredictionMIMIC3()
t30 = ReadmissionPredictionMIMIC3(window=timedelta(days=30))
print("15-day window:", task_cache_name(t15))
print("30-day window:", task_cache_name(t30))
assert task_fingerprint(t15) != task_fingerprint(t30)

ehrshot = task_cache_name(BenchmarkEHRShot(task="guo_los"))
print("EHRShot guo_los:", ehrshot)
assert "/" not in ehrshot
121 changes: 67 additions & 54 deletions pyhealth/datasets/base_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,11 @@
_litdata_merge,
)
from .splitter import Split
from ..tasks.fingerprint import (
processors_fingerprint,
task_cache_name,
write_task_metadata,
)
from ..utils import download_file, preserve_rng_state, set_env

# Set logging level for distributed to ERROR to reduce verbosity
Expand Down Expand Up @@ -580,9 +585,10 @@ def _init_cache_dir(self, cache_dir: str | Path | None) -> Path:
global_event_df.*.building/ # An event table being built; left
# behind only by a killed job
tasks/ # Cached task-specific data
{task_name}_{task_uuid}/ # Cached data for specific task based on task name, schema, and args
{slug}_{task_digest}/ # One task configuration (see set_task)
task_meta.json # Readable spec behind the fingerprint
task_df.ld/ # Intermediate task dataframe based on schema
samples_{proc_uuid}.ld/ # Final processed samples after applying processors
samples_{proc_digest}.ld/ # Final processed samples after applying processors

Returns:
Path: The resolved cache directory path.
Expand Down Expand Up @@ -624,23 +630,12 @@ def _init_cache_dir(self, cache_dir: str | Path | None) -> Path:
def _task_cache_dir(self, task: BaseTask) -> Path:
"""The directory that caches ``task``'s samples for this dataset.

The name holds the task name and a hash of the task's attributes and
schemas, so tasks that differ in any argument get their own cache.
The name holds the task name and the task fingerprint
(:func:`~pyhealth.tasks.fingerprint.task_cache_name`): effective instance
state, class-level configuration, schemas and ``version``, so tasks that
differ in any of them get their own cache.
"""
task_params = json.dumps(
{
**vars(task),
"input_schema": task.input_schema,
"output_schema": task.output_schema,
},
sort_keys=True,
default=str,
)
return (
self.cache_dir
/ "tasks"
/ f"{task.task_name}_{uuid.uuid5(uuid.NAMESPACE_DNS, task_params)}"
)
return self.cache_dir / "tasks" / task_cache_name(task)

def clear_task_cache(self, task: BaseTask | None = None) -> bool:
"""Deletes the cached samples of one task for this dataset.
Expand Down Expand Up @@ -1378,12 +1373,42 @@ def set_task(
"""Processes the base dataset to generate the task-specific sample dataset.
The cache structure is as follows::

{task_name}_{task_uuid}/ # Cached data for specific task based on task name, schema, and args
task_df.ld/ # Intermediate task dataframe based on schema
samples_{proc_uuid}.ld/ # Final processed samples after applying processors
schema.pkl # Saved SampleBuilder schema
split.npz # Sample indices per split part (with split= only)
*.bin # Processed sample files
{slug}_{task_digest}/ # One task configuration
task_meta.json # Readable spec behind the fingerprint
build.lock # Guards concurrent builds
task_df.ld/ # Intermediate task dataframe based on schema
samples_{proc_digest}.ld/ # Final processed samples after applying processors
schema.pkl # Saved SampleBuilder schema
split.npz # Sample indices per split part (with split= only)
*.bin # Processed sample files

``slug`` is ``task_name`` made safe for a path: each run of characters
other than letters, digits, ``.``, ``_`` and ``-`` becomes ``-``, and
the result is cut to 48 characters.
``task_digest`` and ``proc_digest`` are the first 16 hex characters of
``task_fingerprint`` and ``proc_fingerprint``.

``task_fingerprint`` is a digest of everything that determines the
generated samples: the state ``__init__`` leaves on the task (so passing
a default explicitly is not a different config), public class-level
attributes, the input and output schemas, and ``BaseTask.version``.
Changing any of them yields a new directory. What the digest does not
see is listed in :mod:`pyhealth.tasks.fingerprint`. Attributes that do
not affect the output -- ``num_workers``, ``verbose`` -- are excluded,
and a task can exclude more of its own via ``fingerprint_exclude``.

``proc_fingerprint`` covers everything that determines the processed
samples below a given task directory: the pre-fitted processors, the
on-disk layout (``STORAGE_FORMAT``) and, when one is given, the
``split``. The last two matter because a split changes which patients
fit the processors, and a layout change makes old ``*.bin`` files
unreadable; neither may share a directory with a different value.

Because the digest is opaque, ``task_meta.json`` records the full spec
in readable form: consult it to see which parameter produced a given
directory. Note that editing ``__call__`` does *not* change the
fingerprint by itself -- bump ``version`` on the task when its logic
changes, or existing caches will be silently reused.

Args:
task (Optional[BaseTask]): The task to set. Uses default task if None.
Expand Down Expand Up @@ -1433,39 +1458,27 @@ def set_task(
cache_dir = self._task_cache_dir(task)
cache_dir.mkdir(parents=True, exist_ok=True)

proc_params = json.dumps(
{
"input_processors": (
{
f"{k}_{v.__class__.__name__}": vars(v)
for k, v in input_processors.items()
}
if input_processors
else None
),
"output_processors": (
{
f"{k}_{v.__class__.__name__}": vars(v)
for k, v in output_processors.items()
}
if output_processors
else None
),
# Layout of processed samples on disk; a new layout gets a new cache.
"storage_format": STORAGE_FORMAT,
# Only present with a split, so existing unsplit caches keep their key.
**({"split": split.to_dict()} if split is not None else {}),
},
sort_keys=True,
default=str,
)

task_df_path = Path(cache_dir) / "task_df.ld"
samples_path = (
Path(cache_dir)
/ f"samples_{uuid.uuid5(uuid.NAMESPACE_DNS, proc_params)}.ld"
proc_fingerprint = processors_fingerprint(
input_processors,
output_processors,
# A new on-disk layout cannot reuse samples written under the old
# one, and a split decides which patients fit the processors.
storage_format=STORAGE_FORMAT,
split=split.to_dict() if split is not None else None,
)
samples_path = Path(cache_dir) / f"samples_{proc_fingerprint[:16]}.ld"

# The cache key is opaque by construction; the sidecar makes it
# auditable. Written before the build so a crashed build still leaves
# a directory that explains what it was trying to produce.
meta_path = write_task_metadata(cache_dir, task)
logger.info(
"Task cache key %s -- derived from instance state, schemas and task "
"version. Full spec: %s",
Path(cache_dir).name, # already task_cache_name(task)
meta_path,
)
logger.info(f"Task cache paths: task_df={task_df_path}, samples={samples_path}")

task_df_path.mkdir(parents=True, exist_ok=True)
Expand Down
15 changes: 15 additions & 0 deletions pyhealth/tasks/base_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ class BaseTask(ABC):
implement ``__call__``. They may also describe themselves with
:meth:`task_card`.

Instance state (as left by ``__init__``), class-level configuration, and
``version`` are part of the ``set_task`` cache key. Bump ``version`` when
``__call__`` or ``pre_filter`` changes in a way that alters generated
samples.

Examples:
>>> class Mortality(BaseTask):
... task_name = "mortality"
Expand All @@ -30,6 +35,16 @@ class BaseTask(ABC):
input_schema: Dict[str, Union[str, Type]]
output_schema: Dict[str, Union[str, Type]]

#: Bump when ``__call__`` or ``pre_filter`` logic changes in a way that
#: alters the generated samples. Instance state alone cannot detect this.
version: str = "1"

#: Attribute names that do not affect the generated samples and must not
#: invalidate the cache (e.g. ``num_workers``, ``verbose``). Denylist, not
#: allowlist: forgetting an entry here costs a spurious rebuild, whereas
#: forgetting to allowlist a semantic arg silently reuses a stale cache.
fingerprint_exclude: frozenset[str] = frozenset()

def __init__(
self,
code_mapping: Optional[Dict[str, Tuple[str, str]]] = None,
Expand Down
Loading
Loading