cs-lab 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cs_lab/__init__.py +146 -0
- cs_lab/__main__.py +5 -0
- cs_lab/_version.py +24 -0
- cs_lab/cli.py +325 -0
- cs_lab/config.py +192 -0
- cs_lab/datamaestro.py +33 -0
- cs_lab/hf.py +351 -0
- cs_lab/machine.py +328 -0
- cs_lab/notebook.py +21 -0
- cs_lab/profile.py +276 -0
- cs_lab/pyterrier.py +29 -0
- cs_lab/resources.py +211 -0
- cs_lab/scan.py +772 -0
- cs_lab/web.py +180 -0
- cs_lab-1.0.0.dist-info/METADATA +374 -0
- cs_lab-1.0.0.dist-info/RECORD +19 -0
- cs_lab-1.0.0.dist-info/WHEEL +4 -0
- cs_lab-1.0.0.dist-info/entry_points.txt +2 -0
- cs_lab-1.0.0.dist-info/licenses/LICENSE +21 -0
cs_lab/__init__.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""cs-lab: what a teaching notebook needs from the machine it runs on.
|
|
2
|
+
|
|
3
|
+
Three questions a practical has to answer, kept apart:
|
|
4
|
+
|
|
5
|
+
*How much compute to spend* — a :class:`Profile` ladder the course declares,
|
|
6
|
+
selected with ``NOTEBOOK_PROFILE`` or from the in-notebook chooser::
|
|
7
|
+
|
|
8
|
+
from cs_lab import Profile as BaseProfile
|
|
9
|
+
|
|
10
|
+
class Profile(BaseProfile):
|
|
11
|
+
FAST_TEST = 0
|
|
12
|
+
SMALL = 1
|
|
13
|
+
LOW_GPU = 2
|
|
14
|
+
|
|
15
|
+
*What the machine offers* — device, dtype, and whether ``bitsandbytes`` or
|
|
16
|
+
``vLLM`` actually work here (:func:`hardware`, see :mod:`cs_lab.machine`)::
|
|
17
|
+
|
|
18
|
+
hw = hardware(Profile) # also shows the chooser, in a notebook
|
|
19
|
+
model = load_hf_model(Profile.pick(...), AutoModelForCausalLM, dtype=hw.dtype)
|
|
20
|
+
model.to(hw.device)
|
|
21
|
+
|
|
22
|
+
*Where the weights come from* — a shared local cache, falling back to the Hub,
|
|
23
|
+
so thirty laptops in a room do not each download the same model.
|
|
24
|
+
|
|
25
|
+
Notebook side::
|
|
26
|
+
|
|
27
|
+
from cs_lab import load_hf_model, load_hf_tokenizer, load_hf_dataset, HFModel
|
|
28
|
+
|
|
29
|
+
Course side (declare what to pre-download)::
|
|
30
|
+
|
|
31
|
+
from cs_lab import make_hf_model_resource, make_hf_dataset_resource
|
|
32
|
+
RESOURCES = {"practical1": [make_hf_model_resource("gpt2"), ...]}
|
|
33
|
+
|
|
34
|
+
then ``cs-lab cache download --from mycourse.resources:RESOURCES``.
|
|
35
|
+
|
|
36
|
+
For course data that is not a HuggingFace model/dataset (a tarball published
|
|
37
|
+
on a course web server, say), use :func:`cached_download` instead -- same
|
|
38
|
+
``CS_LAB_CACHE_PATH`` root and cache-miss policy, with a plain relative-path
|
|
39
|
+
layout rather than the HuggingFace one.
|
|
40
|
+
|
|
41
|
+
``cs-lab cache scan sources/`` reads the loader calls back out of the sources, so
|
|
42
|
+
that a declaration can be written from them (``--emit``) and kept honest
|
|
43
|
+
(``cs-lab cache check sources/ --declaration mycourse/resources.py``).
|
|
44
|
+
|
|
45
|
+
Configure the cache root with ``CS_LAB_CACHE_PATH`` (see :mod:`cs_lab.config`).
|
|
46
|
+
|
|
47
|
+
:class:`Profile` is the base for a course's compute ladder (see
|
|
48
|
+
:mod:`cs_lab.profile`); the scanner reads ``Profile.pick(...)`` calls to
|
|
49
|
+
learn which of several models a notebook may load.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
from .config import (
|
|
53
|
+
ENV_ENFORCE,
|
|
54
|
+
ENV_PATH,
|
|
55
|
+
CacheMissError,
|
|
56
|
+
get_cache_path,
|
|
57
|
+
is_enforce_mode,
|
|
58
|
+
)
|
|
59
|
+
from .datamaestro import make_datamaestro_resource
|
|
60
|
+
from .hf import (
|
|
61
|
+
HFModel,
|
|
62
|
+
load_hf_dataset,
|
|
63
|
+
load_hf_model,
|
|
64
|
+
load_hf_processor,
|
|
65
|
+
load_hf_tokenizer,
|
|
66
|
+
make_hf_dataset_resource,
|
|
67
|
+
make_hf_model_resource,
|
|
68
|
+
make_hf_processor_resource,
|
|
69
|
+
make_hf_tokenizer_resource,
|
|
70
|
+
)
|
|
71
|
+
from .machine import ENV_BACKEND, Hardware, add_state_note, hardware
|
|
72
|
+
from .notebook import is_notebook
|
|
73
|
+
from .profile import ENV_PROFILE, Profile, current_ladder
|
|
74
|
+
from .pyterrier import make_pyterrier_dataset_resource
|
|
75
|
+
from .resources import (
|
|
76
|
+
DownloadableResource,
|
|
77
|
+
FunctionalResource,
|
|
78
|
+
Resource,
|
|
79
|
+
Resources,
|
|
80
|
+
download_resources,
|
|
81
|
+
format_resources,
|
|
82
|
+
merge_resources,
|
|
83
|
+
select_resources,
|
|
84
|
+
)
|
|
85
|
+
from .scan import (
|
|
86
|
+
ScannedResource,
|
|
87
|
+
compare,
|
|
88
|
+
emit_section,
|
|
89
|
+
parse_declaration,
|
|
90
|
+
scan_paths,
|
|
91
|
+
)
|
|
92
|
+
from .web import cached_download
|
|
93
|
+
|
|
94
|
+
try:
|
|
95
|
+
from ._version import __version__
|
|
96
|
+
except ImportError: # pragma: no cover - not installed from a build
|
|
97
|
+
__version__ = "0.0.0+unknown"
|
|
98
|
+
|
|
99
|
+
__all__ = [
|
|
100
|
+
"__version__",
|
|
101
|
+
# config
|
|
102
|
+
"ENV_PATH",
|
|
103
|
+
"ENV_ENFORCE",
|
|
104
|
+
"CacheMissError",
|
|
105
|
+
"get_cache_path",
|
|
106
|
+
"is_enforce_mode",
|
|
107
|
+
# profiles
|
|
108
|
+
"ENV_PROFILE",
|
|
109
|
+
"Profile",
|
|
110
|
+
"current_ladder",
|
|
111
|
+
# the machine underneath
|
|
112
|
+
"ENV_BACKEND",
|
|
113
|
+
"Hardware",
|
|
114
|
+
"hardware",
|
|
115
|
+
"add_state_note",
|
|
116
|
+
"is_notebook",
|
|
117
|
+
# loading
|
|
118
|
+
"HFModel",
|
|
119
|
+
"load_hf_dataset",
|
|
120
|
+
"load_hf_model",
|
|
121
|
+
"load_hf_processor",
|
|
122
|
+
"load_hf_tokenizer",
|
|
123
|
+
# resources
|
|
124
|
+
"Resource",
|
|
125
|
+
"DownloadableResource",
|
|
126
|
+
"FunctionalResource",
|
|
127
|
+
"Resources",
|
|
128
|
+
"download_resources",
|
|
129
|
+
"format_resources",
|
|
130
|
+
"merge_resources",
|
|
131
|
+
"select_resources",
|
|
132
|
+
"make_hf_dataset_resource",
|
|
133
|
+
"make_hf_model_resource",
|
|
134
|
+
"make_hf_processor_resource",
|
|
135
|
+
"make_hf_tokenizer_resource",
|
|
136
|
+
"make_pyterrier_dataset_resource",
|
|
137
|
+
"make_datamaestro_resource",
|
|
138
|
+
# scanning the sources that load them
|
|
139
|
+
"ScannedResource",
|
|
140
|
+
"compare",
|
|
141
|
+
"emit_section",
|
|
142
|
+
"parse_declaration",
|
|
143
|
+
"scan_paths",
|
|
144
|
+
# generic URL/archive caching
|
|
145
|
+
"cached_download",
|
|
146
|
+
]
|
cs_lab/__main__.py
ADDED
cs_lab/_version.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# file generated by vcs-versioning
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"__version__",
|
|
7
|
+
"__version_tuple__",
|
|
8
|
+
"version",
|
|
9
|
+
"version_tuple",
|
|
10
|
+
"__commit_id__",
|
|
11
|
+
"commit_id",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
version: str
|
|
15
|
+
__version__: str
|
|
16
|
+
__version_tuple__: tuple[int | str, ...]
|
|
17
|
+
version_tuple: tuple[int | str, ...]
|
|
18
|
+
commit_id: str | None
|
|
19
|
+
__commit_id__: str | None
|
|
20
|
+
|
|
21
|
+
__version__ = version = '1.0.0'
|
|
22
|
+
__version_tuple__ = version_tuple = (1, 0, 0)
|
|
23
|
+
|
|
24
|
+
__commit_id__ = commit_id = None
|
cs_lab/cli.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
"""Command line: inspect the cache, list, download and audit declared resources.
|
|
2
|
+
|
|
3
|
+
Resources are given with ``--from module:attribute`` (or ``--from path.py``,
|
|
4
|
+
which reads ``RESOURCES`` from a file that need not be importable): the module
|
|
5
|
+
is imported and the attribute read from it. It must be a resource mapping
|
|
6
|
+
(``{section: [Resource, ...]}``) or a zero-argument callable returning one::
|
|
7
|
+
|
|
8
|
+
cs-lab cache info
|
|
9
|
+
cs-lab cache list --from llm_course.resources:RESOURCES
|
|
10
|
+
cs-lab cache list --from src/llm_course/resources.py
|
|
11
|
+
cs-lab cache download --from llm_course.resources:get_resources --section practical2
|
|
12
|
+
cs-lab cache download --from llm_course.resources:RESOURCES --key gpt2
|
|
13
|
+
|
|
14
|
+
``scan`` and ``check`` work the other way round, on the *sources* that load the
|
|
15
|
+
resources: they read the loader calls out of the code, so that a declaration
|
|
16
|
+
can be written from them (``scan --emit``) and kept honest (``check``)::
|
|
17
|
+
|
|
18
|
+
cs-lab cache scan sources/
|
|
19
|
+
cs-lab cache scan sources/ --emit 02-generation
|
|
20
|
+
cs-lab cache check sources/ --declaration mycourse/resources.py
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import argparse
|
|
26
|
+
import importlib
|
|
27
|
+
import importlib.util
|
|
28
|
+
import logging
|
|
29
|
+
import sys
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
from typing import List, Optional, Sequence, Tuple
|
|
32
|
+
|
|
33
|
+
from . import config
|
|
34
|
+
from .resources import Resources, download_resources, format_resources
|
|
35
|
+
from .scan import DEFAULT_GUARDS, compare, emit_section, parse_declaration, scan_paths
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _import_path(path: Path) -> object:
|
|
39
|
+
"""Import a ``.py`` file directly, without it being on ``sys.path``."""
|
|
40
|
+
if not path.is_file():
|
|
41
|
+
raise SystemExit(f"no such file: {path}")
|
|
42
|
+
name = f"_cs_lab_resources_{abs(hash(str(path.resolve())))}"
|
|
43
|
+
spec = importlib.util.spec_from_file_location(name, path)
|
|
44
|
+
if spec is None or spec.loader is None:
|
|
45
|
+
raise SystemExit(f"cannot import {path}")
|
|
46
|
+
module = importlib.util.module_from_spec(spec)
|
|
47
|
+
sys.modules[name] = module
|
|
48
|
+
try:
|
|
49
|
+
spec.loader.exec_module(module)
|
|
50
|
+
except Exception as exc: # a bad declaration file, not our problem to fix
|
|
51
|
+
del sys.modules[name]
|
|
52
|
+
raise SystemExit(f"{path}: {exc}") from exc
|
|
53
|
+
return module
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _split_spec(spec: str) -> Tuple[str, str]:
|
|
57
|
+
"""``module:attr``, ``file.py`` or ``file.py:attr`` -> (target, attribute)."""
|
|
58
|
+
head, sep, tail = spec.rpartition(":")
|
|
59
|
+
if sep and head.endswith(".py"):
|
|
60
|
+
return head, tail # file.py:attr
|
|
61
|
+
if spec.endswith(".py"):
|
|
62
|
+
return spec, "RESOURCES" # file.py, attribute implied
|
|
63
|
+
module_name, sep, attr_path = spec.partition(":")
|
|
64
|
+
if not sep or not attr_path:
|
|
65
|
+
raise SystemExit(
|
|
66
|
+
f"invalid resource spec {spec!r}: expected module:attribute, "
|
|
67
|
+
"path/to/resources.py, or path/to/resources.py:attribute"
|
|
68
|
+
)
|
|
69
|
+
return module_name, attr_path
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def load_resources(spec: str) -> Resources:
|
|
73
|
+
"""Resolve ``module:attribute`` (or a ``.py`` path) to a resource mapping."""
|
|
74
|
+
target, attr_path = _split_spec(spec)
|
|
75
|
+
if target.endswith(".py"):
|
|
76
|
+
obj: object = _import_path(Path(target))
|
|
77
|
+
else:
|
|
78
|
+
obj = importlib.import_module(target)
|
|
79
|
+
for attr in attr_path.split("."):
|
|
80
|
+
obj = getattr(obj, attr)
|
|
81
|
+
if callable(obj):
|
|
82
|
+
obj = obj()
|
|
83
|
+
if not isinstance(obj, dict):
|
|
84
|
+
raise SystemExit(f"{spec} did not yield a {{section: [resources]}} mapping")
|
|
85
|
+
return obj
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _load_all(specs: Sequence[str]) -> List[Tuple[str, Resources]]:
|
|
89
|
+
return [(spec, load_resources(spec)) for spec in specs]
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def cmd_info(args: argparse.Namespace) -> int:
|
|
93
|
+
print(config.describe())
|
|
94
|
+
return 0
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def cmd_list(args: argparse.Namespace) -> int:
|
|
98
|
+
for spec, resources in _load_all(args.resources):
|
|
99
|
+
print(f"{spec}:")
|
|
100
|
+
if not resources:
|
|
101
|
+
print(" (no resources)")
|
|
102
|
+
continue
|
|
103
|
+
print("\n".join(format_resources(resources, indent=" ")))
|
|
104
|
+
return 0
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def cmd_download(args: argparse.Namespace) -> int:
|
|
108
|
+
root = config.get_cache_path()
|
|
109
|
+
if root is None:
|
|
110
|
+
logging.warning(
|
|
111
|
+
"%s is not set: resources will go to the default HuggingFace cache "
|
|
112
|
+
"(~/.cache/huggingface). Set it to populate a shared cache.",
|
|
113
|
+
config.ENV_PATH,
|
|
114
|
+
)
|
|
115
|
+
else:
|
|
116
|
+
print(f"Cache location: {root}")
|
|
117
|
+
|
|
118
|
+
failed: List[Tuple[str, object, Exception]] = []
|
|
119
|
+
with config.hub_online():
|
|
120
|
+
for spec, resources in _load_all(args.resources):
|
|
121
|
+
if args.section and args.section not in resources:
|
|
122
|
+
logging.warning("%s: no section %r", spec, args.section)
|
|
123
|
+
continue
|
|
124
|
+
try:
|
|
125
|
+
download_resources(
|
|
126
|
+
resources,
|
|
127
|
+
section=args.section,
|
|
128
|
+
key=args.key,
|
|
129
|
+
include_optional=args.optional,
|
|
130
|
+
keep_going=args.keep_going,
|
|
131
|
+
failures=failed,
|
|
132
|
+
)
|
|
133
|
+
except Exception:
|
|
134
|
+
if not args.keep_going:
|
|
135
|
+
raise
|
|
136
|
+
failed.append((spec, None, sys.exc_info()[1]))
|
|
137
|
+
logging.exception("%s: download failed", spec)
|
|
138
|
+
|
|
139
|
+
if failed:
|
|
140
|
+
print(f"\n{len(failed)} resource(s) could not be downloaded:")
|
|
141
|
+
for section_name, resource, exc in failed:
|
|
142
|
+
name = getattr(resource, "key", section_name)
|
|
143
|
+
print(f" - {section_name}/{name}: {exc}")
|
|
144
|
+
return 1
|
|
145
|
+
return 0
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _scan(args: argparse.Namespace):
|
|
149
|
+
search_paths = list(args.search_path or [])
|
|
150
|
+
for path in args.sources:
|
|
151
|
+
root = path if path.is_dir() else path.parent
|
|
152
|
+
for candidate in (root, root.parent / "src", root.parent):
|
|
153
|
+
if candidate.is_dir() and candidate not in search_paths:
|
|
154
|
+
search_paths.append(candidate)
|
|
155
|
+
return scan_paths(args.sources, guards=args.guard, search_paths=search_paths)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def cmd_scan(args: argparse.Namespace) -> int:
|
|
159
|
+
scanned = _scan(args)
|
|
160
|
+
if args.emit is not None:
|
|
161
|
+
sections = [args.emit] if args.emit else sorted(scanned)
|
|
162
|
+
unknown = [s for s in sections if s not in scanned]
|
|
163
|
+
if unknown:
|
|
164
|
+
raise SystemExit(f"no such section: {', '.join(unknown)}")
|
|
165
|
+
print("RESOURCES = {")
|
|
166
|
+
for section in sections:
|
|
167
|
+
print(emit_section(section, scanned[section]))
|
|
168
|
+
print("}")
|
|
169
|
+
return 0
|
|
170
|
+
|
|
171
|
+
for section in sorted(scanned):
|
|
172
|
+
print(f"{section}:")
|
|
173
|
+
for resource in sorted(scanned[section], key=lambda r: (r.kind, r.key)):
|
|
174
|
+
note = " (bypasses cs_lab)" if resource.bypass else ""
|
|
175
|
+
print(f" - {resource}{note}")
|
|
176
|
+
return 0
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def cmd_check(args: argparse.Namespace) -> int:
|
|
180
|
+
scanned = _scan(args)
|
|
181
|
+
try:
|
|
182
|
+
declared = parse_declaration(args.declaration)
|
|
183
|
+
except (OSError, SyntaxError, ValueError) as exc:
|
|
184
|
+
raise SystemExit(str(exc)) from exc
|
|
185
|
+
|
|
186
|
+
errors, warnings = compare(scanned, declared)
|
|
187
|
+
for warning in warnings:
|
|
188
|
+
print(f"warning: {warning}")
|
|
189
|
+
for error in errors:
|
|
190
|
+
print(f"error: {error}")
|
|
191
|
+
|
|
192
|
+
if errors:
|
|
193
|
+
print(
|
|
194
|
+
f"\n{args.declaration} is out of sync ({len(errors)} difference(s)); "
|
|
195
|
+
"`cs-lab cache scan --emit <section>` prints a skeleton to start from."
|
|
196
|
+
)
|
|
197
|
+
return 1
|
|
198
|
+
total = sum(1 for items in scanned.values() for r in items if not r.bypass)
|
|
199
|
+
print(f"{args.declaration} matches the sources ({total} cached loads).")
|
|
200
|
+
return 0
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
204
|
+
parser = argparse.ArgumentParser(
|
|
205
|
+
prog="cs-lab",
|
|
206
|
+
description=(
|
|
207
|
+
"What a teaching notebook needs from the machine it runs on. The "
|
|
208
|
+
"compute-profile ladder and hardware detection are library-only "
|
|
209
|
+
"(`from cs_lab import Profile, hardware`); what has a command "
|
|
210
|
+
"line is the shared resource cache, below."
|
|
211
|
+
),
|
|
212
|
+
)
|
|
213
|
+
parser.add_argument("-v", "--verbose", action="store_true", help="debug logging")
|
|
214
|
+
groups = parser.add_subparsers(dest="group", required=True)
|
|
215
|
+
|
|
216
|
+
# Everything here is about the resource cache, and says so: the package
|
|
217
|
+
# covers more than that now (a profile ladder, hardware detection), and a
|
|
218
|
+
# later group must not have to compete with `list` or `check` for a name.
|
|
219
|
+
cache = groups.add_parser(
|
|
220
|
+
"cache",
|
|
221
|
+
help="the shared resource cache: inspect it, declare and download what "
|
|
222
|
+
"a course needs",
|
|
223
|
+
description=__doc__,
|
|
224
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
225
|
+
)
|
|
226
|
+
sub = cache.add_subparsers(dest="command", required=True)
|
|
227
|
+
|
|
228
|
+
p_info = sub.add_parser("info", help="show the cache configuration")
|
|
229
|
+
p_info.set_defaults(func=cmd_info)
|
|
230
|
+
|
|
231
|
+
def add_from(p: argparse.ArgumentParser) -> None:
|
|
232
|
+
p.add_argument(
|
|
233
|
+
"--from",
|
|
234
|
+
dest="resources",
|
|
235
|
+
metavar="MODULE:ATTR|FILE.py",
|
|
236
|
+
action="append",
|
|
237
|
+
required=True,
|
|
238
|
+
help="resource mapping or callable returning one; a .py path is "
|
|
239
|
+
"imported directly, its RESOURCES read unless :ATTR says otherwise "
|
|
240
|
+
"(repeatable)",
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
p_list = sub.add_parser("list", help="list declared resources")
|
|
244
|
+
add_from(p_list)
|
|
245
|
+
p_list.set_defaults(func=cmd_list)
|
|
246
|
+
|
|
247
|
+
p_dl = sub.add_parser("download", help="download declared resources")
|
|
248
|
+
add_from(p_dl)
|
|
249
|
+
p_dl.add_argument("--section", help="only this section (lecture, practical...)")
|
|
250
|
+
p_dl.add_argument("--key", help="only the resource with this key")
|
|
251
|
+
p_dl.add_argument(
|
|
252
|
+
"--optional", action="store_true", help="include optional resources"
|
|
253
|
+
)
|
|
254
|
+
p_dl.add_argument(
|
|
255
|
+
"--keep-going",
|
|
256
|
+
action="store_true",
|
|
257
|
+
help="continue with the next --from group when a download fails",
|
|
258
|
+
)
|
|
259
|
+
p_dl.set_defaults(func=cmd_download)
|
|
260
|
+
|
|
261
|
+
def add_scan(p: argparse.ArgumentParser) -> None:
|
|
262
|
+
p.add_argument(
|
|
263
|
+
"sources",
|
|
264
|
+
nargs="+",
|
|
265
|
+
type=Path,
|
|
266
|
+
metavar="PATH",
|
|
267
|
+
help="source files, or directories whose *.py are scanned",
|
|
268
|
+
)
|
|
269
|
+
p.add_argument(
|
|
270
|
+
"--guard",
|
|
271
|
+
action="append",
|
|
272
|
+
default=list(DEFAULT_GUARDS),
|
|
273
|
+
metavar="NAME",
|
|
274
|
+
help="`if NAME:` marks an optional stand-in (default: %(default)s)",
|
|
275
|
+
)
|
|
276
|
+
p.add_argument(
|
|
277
|
+
"--search-path",
|
|
278
|
+
action="append",
|
|
279
|
+
type=Path,
|
|
280
|
+
metavar="DIR",
|
|
281
|
+
help="root under which imported modules are found and scanned too",
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
p_scan = sub.add_parser("scan", help="list the resources the sources load")
|
|
285
|
+
add_scan(p_scan)
|
|
286
|
+
p_scan.add_argument(
|
|
287
|
+
"--emit",
|
|
288
|
+
nargs="?",
|
|
289
|
+
const="",
|
|
290
|
+
metavar="SECTION",
|
|
291
|
+
help="print a declaration skeleton (all sections, or just SECTION)",
|
|
292
|
+
)
|
|
293
|
+
p_scan.set_defaults(func=cmd_scan)
|
|
294
|
+
|
|
295
|
+
p_check = sub.add_parser(
|
|
296
|
+
"check", help="check a declaration against the sources (exit 1 on drift)"
|
|
297
|
+
)
|
|
298
|
+
add_scan(p_check)
|
|
299
|
+
p_check.add_argument(
|
|
300
|
+
"--declaration",
|
|
301
|
+
required=True,
|
|
302
|
+
type=Path,
|
|
303
|
+
metavar="FILE",
|
|
304
|
+
help="Python file holding the RESOURCES mapping",
|
|
305
|
+
)
|
|
306
|
+
p_check.set_defaults(func=cmd_check)
|
|
307
|
+
return parser
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
311
|
+
args = build_parser().parse_args(argv)
|
|
312
|
+
# Only our own logger talks at INFO: setting the root logger there as well
|
|
313
|
+
# turned every HTTP request huggingface_hub makes into a line of output.
|
|
314
|
+
logging.basicConfig(
|
|
315
|
+
level=logging.DEBUG if args.verbose else logging.WARNING,
|
|
316
|
+
format="%(levelname)s:%(name)s:%(message)s",
|
|
317
|
+
)
|
|
318
|
+
logging.getLogger("cs_lab").setLevel(
|
|
319
|
+
logging.DEBUG if args.verbose else logging.INFO
|
|
320
|
+
)
|
|
321
|
+
return args.func(args)
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
if __name__ == "__main__": # pragma: no cover
|
|
325
|
+
sys.exit(main())
|
cs_lab/config.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""Cache location, layout and cache-miss policy.
|
|
2
|
+
|
|
3
|
+
Environment variables
|
|
4
|
+
---------------------
|
|
5
|
+
``CS_LAB_CACHE_PATH``
|
|
6
|
+
Root of the shared local cache. When unset, this library adds no caching
|
|
7
|
+
of its own: loaders forward to ``from_pretrained`` / ``load_dataset``
|
|
8
|
+
unchanged, so HuggingFace's usual cache (``~/.cache/huggingface``) applies.
|
|
9
|
+
``CS_LAB_CACHE_ENFORCE``
|
|
10
|
+
If set to any value, a cache miss raises :class:`CacheMissError` instead of
|
|
11
|
+
falling back to the remote source. Useful to verify that everything a
|
|
12
|
+
notebook needs is in the cache.
|
|
13
|
+
|
|
14
|
+
Both were called something else before: ``CS_LAB_PATH`` / ``CS_LAB_ENFORCE``
|
|
15
|
+
until the cache became one part of this package rather than all of it, and
|
|
16
|
+
``CACHED_HUB_PATH`` / ``CACHED_HUB_ENFORCE`` before the rename. A classroom
|
|
17
|
+
machine exports them from a shell profile this code cannot edit, so they are
|
|
18
|
+
still read — once, with a word on stderr. A shared cache that silently stops
|
|
19
|
+
being used is an afternoon of downloads in a room of thirty.
|
|
20
|
+
|
|
21
|
+
On-disk layout
|
|
22
|
+
--------------
|
|
23
|
+
Kept identical to the historical ``master_mind`` layout so existing caches
|
|
24
|
+
keep working::
|
|
25
|
+
|
|
26
|
+
<root>/huggingface/models/<id>/ model.save_pretrained()
|
|
27
|
+
<root>/huggingface/tokenizers/<id>/ tokenizer.save_pretrained()
|
|
28
|
+
<root>/huggingface/processors/<id>/ processor.save_pretrained()
|
|
29
|
+
<root>/huggingface/datasets/<id>[-<name>]/<split>/ dataset.save_to_disk()
|
|
30
|
+
<root>/huggingface/ HF ``cache_dir`` for fallbacks
|
|
31
|
+
|
|
32
|
+
``<id>`` is the HuggingFace identifier with ``/`` replaced by ``-``. A directory
|
|
33
|
+
counts as complete only when it contains the marker file ``.downloaded.ok``,
|
|
34
|
+
written after a successful download.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
from __future__ import annotations
|
|
38
|
+
|
|
39
|
+
import logging
|
|
40
|
+
import os
|
|
41
|
+
from contextlib import contextmanager
|
|
42
|
+
from pathlib import Path
|
|
43
|
+
from typing import Iterator, Optional
|
|
44
|
+
|
|
45
|
+
logger = logging.getLogger("cs_lab")
|
|
46
|
+
|
|
47
|
+
ENV_PATH = "CS_LAB_CACHE_PATH"
|
|
48
|
+
ENV_ENFORCE = "CS_LAB_CACHE_ENFORCE"
|
|
49
|
+
#: Older spellings of each variable, tried in turn: ``CS_LAB_*`` from before
|
|
50
|
+
#: the cache commands were grouped, and ``CACHED_HUB_*`` from before the
|
|
51
|
+
#: package was renamed. A classroom machine exports them from a shell profile
|
|
52
|
+
#: this code cannot edit, and a shared cache that silently stops being used is
|
|
53
|
+
#: an afternoon of downloads in a room of thirty.
|
|
54
|
+
LEGACY_ENV = {
|
|
55
|
+
ENV_PATH: ("CS_LAB_PATH", "CACHED_HUB_PATH"),
|
|
56
|
+
ENV_ENFORCE: ("CS_LAB_ENFORCE", "CACHED_HUB_ENFORCE"),
|
|
57
|
+
}
|
|
58
|
+
_warned: set[str] = set()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _environ(name: str) -> Optional[str]:
|
|
62
|
+
"""The variable's value, falling back to its older spellings."""
|
|
63
|
+
value = os.environ.get(name)
|
|
64
|
+
if value is not None:
|
|
65
|
+
return value
|
|
66
|
+
for legacy in LEGACY_ENV.get(name, ()):
|
|
67
|
+
value = os.environ.get(legacy)
|
|
68
|
+
if value is None:
|
|
69
|
+
continue
|
|
70
|
+
if legacy not in _warned:
|
|
71
|
+
_warned.add(legacy)
|
|
72
|
+
logger.warning("%s is the old name of %s; read it anyway", legacy, name)
|
|
73
|
+
return value
|
|
74
|
+
return None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
#: Marker file written in a resource directory once its download completed.
|
|
78
|
+
DOWNLOAD_MARKER = ".downloaded.ok"
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class CacheMissError(Exception):
|
|
82
|
+
"""Raised on a cache miss when enforce mode is on (``CS_LAB_CACHE_ENFORCE``)."""
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def get_cache_path() -> Optional[Path]:
|
|
86
|
+
"""Return the cache root, or ``None`` when no cache is configured."""
|
|
87
|
+
value = _environ(ENV_PATH)
|
|
88
|
+
return Path(value) if value else None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def is_enforce_mode() -> bool:
|
|
92
|
+
"""Return True when a cache miss must raise instead of falling back."""
|
|
93
|
+
return _environ(ENV_ENFORCE) is not None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def sanitize_id(resource_id: str) -> str:
|
|
97
|
+
"""Turn a hub identifier (``org/name``) into a directory name (``org-name``)."""
|
|
98
|
+
return resource_id.replace("/", "-")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def get_resource_path(
|
|
102
|
+
provider: str, resource_type: str, resource_id: str, name: Optional[str] = None
|
|
103
|
+
) -> Optional[Path]:
|
|
104
|
+
"""Directory where a resource lives in the cache, or ``None`` if no cache.
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
provider: e.g. ``"huggingface"``
|
|
108
|
+
resource_type: e.g. ``"models"``, ``"tokenizers"``, ``"datasets"``
|
|
109
|
+
resource_id: hub identifier, e.g. ``"distilbert-base-uncased"``
|
|
110
|
+
name: optional configuration name (e.g. ``"sst2"`` for the glue dataset)
|
|
111
|
+
"""
|
|
112
|
+
root = get_cache_path()
|
|
113
|
+
if root is None:
|
|
114
|
+
return None
|
|
115
|
+
safe_id = sanitize_id(resource_id)
|
|
116
|
+
if name:
|
|
117
|
+
safe_id = f"{safe_id}-{name}"
|
|
118
|
+
return root / provider / resource_type / safe_id
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def get_hf_cache_dir() -> Optional[str]:
|
|
122
|
+
"""HuggingFace ``cache_dir`` inside the cache root (created on demand).
|
|
123
|
+
|
|
124
|
+
Used when a resource is not in the local layout and has to be fetched from
|
|
125
|
+
the Hub: it keeps the download inside the shared cache instead of
|
|
126
|
+
``~/.cache/huggingface``. Returns ``None`` when no cache is configured.
|
|
127
|
+
"""
|
|
128
|
+
root = get_cache_path()
|
|
129
|
+
if root is None:
|
|
130
|
+
return None
|
|
131
|
+
cache_dir = root / "huggingface"
|
|
132
|
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
|
133
|
+
return str(cache_dir)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def is_download_complete(path: Path) -> bool:
|
|
137
|
+
"""True when ``path`` holds a completed download (marker file present)."""
|
|
138
|
+
return (path / DOWNLOAD_MARKER).exists()
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def mark_download_complete(path: Path) -> None:
|
|
142
|
+
"""Write the completion marker in ``path``."""
|
|
143
|
+
marker = path / DOWNLOAD_MARKER
|
|
144
|
+
marker.touch()
|
|
145
|
+
os.chmod(marker, 0o444)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def warn_cache_miss(
|
|
149
|
+
resource_type: str, resource_id: str, cache_path: Optional[Path] = None
|
|
150
|
+
) -> None:
|
|
151
|
+
"""Report that ``resource_id`` is not in the local cache.
|
|
152
|
+
|
|
153
|
+
With a configured cache this logs a warning, or raises
|
|
154
|
+
:class:`CacheMissError` in enforce mode. Without a cache it only logs at
|
|
155
|
+
debug level (nothing was expected locally).
|
|
156
|
+
"""
|
|
157
|
+
if cache_path is None:
|
|
158
|
+
cache_path = get_cache_path()
|
|
159
|
+
if cache_path:
|
|
160
|
+
message = (
|
|
161
|
+
f"{resource_type} '{resource_id}' not found in local cache at {cache_path}"
|
|
162
|
+
)
|
|
163
|
+
if is_enforce_mode():
|
|
164
|
+
raise CacheMissError(message)
|
|
165
|
+
logger.warning(message)
|
|
166
|
+
else:
|
|
167
|
+
logger.debug(
|
|
168
|
+
"%s '%s': no local cache configured, set %s to enable",
|
|
169
|
+
resource_type,
|
|
170
|
+
resource_id,
|
|
171
|
+
ENV_PATH,
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@contextmanager
|
|
176
|
+
def hub_online() -> Iterator[None]:
|
|
177
|
+
"""Temporarily lift ``HF_HUB_OFFLINE`` so that downloads can reach the Hub."""
|
|
178
|
+
previous = os.environ.pop("HF_HUB_OFFLINE", None)
|
|
179
|
+
try:
|
|
180
|
+
yield
|
|
181
|
+
finally:
|
|
182
|
+
if previous is not None:
|
|
183
|
+
os.environ["HF_HUB_OFFLINE"] = previous
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def describe() -> str:
|
|
187
|
+
"""One-line human description of the current cache configuration."""
|
|
188
|
+
root = get_cache_path()
|
|
189
|
+
if root is None:
|
|
190
|
+
return f"no local cache ({ENV_PATH} is not set)"
|
|
191
|
+
mode = "enforce" if is_enforce_mode() else "fallback to remote"
|
|
192
|
+
return f"local cache at {root} ({mode})"
|