File size: 2,644 Bytes
0107764
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""Evaluation package of SetCon: recomputes the zero-shot numbers of the paper from the released weights.

  setcon.data        the 18 test sets: download notes, extraction with sha256 checks, model-ready caches
  setcon.protocol    the test protocol: datasets, person groups, gait test, walking frame, seeded context draws
  setcon.references  the setup reference of every device under each reading of the paper
  setcon.evaluate    embeddings, zero-shot predictions and class-mean readout for one seed
  setcon.tables      the paper's numbers (Tab. 1-3, abstract, Sec. 4.3-4.4) from the per-seed results

The model itself is loaded through transformers (remote code in the repository root):

    from setcon import load_model
    model = load_model(seed=1)
"""
from __future__ import annotations

import importlib.util
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[1]
# Hugging Face repositories of the release.
MODEL_REPO = "lschiweck/SetCon"
EVAL_DATA_REPO = "lschiweck/SetCon-eval"
SEEDS = (1, 2, 3)


def _load_processing():
    spec = importlib.util.spec_from_file_location("processing_setcon", REPO_ROOT / "processing_setcon.py")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


processing = _load_processing()


def load_model(seed=1, model=None, device="cpu"):
    """The SetCon checkpoint of one stage-2 seed (1, 2 or 3) via AutoModel with trust_remote_code. `model` is a local
    folder or a hub id; default: the repository this package lives in. Seed 1 is the repository root, seeds 2 and 3
    are the subfolders seed2/ and seed3/. Returns the model in eval mode on `device`."""
    from transformers import AutoModel
    if seed not in SEEDS:
        raise ValueError(f"seed must be one of {SEEDS}")
    kwargs = {} if seed == 1 else {"subfolder": f"seed{seed}"}
    m = AutoModel.from_pretrained(str(model or REPO_ROOT), trust_remote_code=True, **kwargs)
    if m.config.training_seed != seed:
        raise ValueError(f"checkpoint reports training seed {m.config.training_seed}, expected {seed}")
    return m.to(device).eval()


def eval_data_dir(path_or_repo=None):
    """Local folder of the evaluation data (class vectors, person groups, window lists, reference predictions):
    an existing folder is used as it is, otherwise the dataset repository is downloaded from the hub."""
    p = Path(path_or_repo) if path_or_repo else None
    if p is not None and p.is_dir():
        return p
    from huggingface_hub import snapshot_download
    return Path(snapshot_download(repo_id=str(path_or_repo or EVAL_DATA_REPO), repo_type="dataset"))