File size: 6,942 Bytes
ed1debd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
"""Cache verified release files and upload metadata on node-local storage."""

import base64
import concurrent.futures
import hashlib
import json
from pathlib import Path
import tempfile
import threading


def configure_for_release(release_root, payloads, verified_stats=None):
    from huggingface_hub import _local_folder
    from huggingface_hub import _upload_large_folder

    release_root = Path(release_root)
    cache = Path(tempfile.gettempdir()) / "ral_moe_hf_upload_20261124"
    cache.mkdir(parents=True, exist_ok=True)
    original_cache = _local_folder._huggingface_dir
    original_paths = _local_folder.get_local_upload_paths
    original_metadata = _upload_large_folder.read_upload_metadata
    original_operation = _upload_large_folder._build_hacky_operation
    original_filter = _upload_large_folder.filter_repo_objects
    original_stat = Path.stat
    indexed = {row["destination_relative_path"]: row for row in payloads}
    payload_cache = cache / "payloads"
    payload_cache.mkdir(exist_ok=True)
    sample_index = cache / "large_file_samples.json"
    prior_samples = json.loads(sample_index.read_text()) if sample_index.exists() else {}
    source_stats = dict(verified_stats or {})

    def prepare_payload(row):
        name = row["destination_relative_path"]
        source = release_root / name
        size = int(row["bytes"])
        digest = row["sha256"]
        snapshot = source_stats.get(name)
        if snapshot is None:
            snapshot = original_stat(source)
        assert snapshot.st_size == size, name
        if "source_mtime_ns" in row:
            assert snapshot.st_mtime_ns == int(row["source_mtime_ns"]), name
        if size <= 1024 * 1024:
            cached = payload_cache / digest
            content = cached.read_bytes() if cached.is_file() else None
            if content is None or len(content) != size or hashlib.sha256(content).hexdigest() != digest:
                with source.open("rb", buffering=0) as stream:
                    content = stream.read()
                assert len(content) == size and hashlib.sha256(content).hexdigest() == digest, name
                temporary = cached.with_name(cached.name + f".{threading.get_ident()}.tmp")
                temporary.write_bytes(content)
                temporary.replace(cached)
            return name, content[:512], cached, snapshot
        encoded = prior_samples.get(digest)
        if encoded is None:
            with source.open("rb", buffering=0) as stream:
                sample = stream.read(512)
        else:
            sample = base64.b64decode(encoded, validate=True)
        assert len(sample) == min(512, size), name
        return name, sample, source, snapshot

    samples = {}
    cached_paths = {}
    with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
        futures = [executor.submit(prepare_payload, row) for row in payloads]
        for number, future in enumerate(concurrent.futures.as_completed(futures), 1):
            name, sample, cached, snapshot = future.result()
            samples[name] = sample
            cached_paths[name] = cached
            source_stats[name] = snapshot
            if number % 5000 == 0 or number == len(payloads):
                print(f"LOCAL_UPLOAD_CACHE_PROGRESS files={number}/{len(payloads)}", flush=True)
    sample_index.write_text(json.dumps({
        row["sha256"]: base64.b64encode(samples[name]).decode("ascii")
        for name, row in indexed.items() if int(row["bytes"]) > 1024 * 1024
    }))

    extras = [release_root / "code_and_checkpoints/README.md", release_root / "simulation_data/README.md"]
    metadata_dir = release_root / "code_and_checkpoints/release_metadata"
    if metadata_dir.is_dir():
        extras.extend(path for path in metadata_dir.rglob("*") if path.is_file())
    extra_names = [path.relative_to(release_root).as_posix() for path in extras if path.is_file()]
    selected_names = list(dict.fromkeys([*indexed, *extra_names]))
    stat_snapshots = {str(release_root / name): value for name, value in source_stats.items()}

    def snapshot_stat(path, *args, **kwargs):
        if not args and kwargs.get("follow_symlinks", True):
            snapshot = stat_snapshots.get(str(path))
            if snapshot is not None:
                return snapshot
        return original_stat(path, *args, **kwargs)

    def selected_release_files(objects, *args, **kwargs):
        # The manifest is the complete curated payload inventory. Avoid a second
        # serial NFS traversal while retaining the SDK's normal ignore rules.
        return original_filter(selected_names, *args, **kwargs)

    def cache_directory(local_dir):
        return cache if Path(local_dir) == release_root else original_cache(local_dir)

    def upload_paths(local_dir, filename):
        if Path(local_dir) != release_root:
            return original_paths(local_dir, filename)
        relative = Path(filename)
        assert not relative.is_absolute() and ".." not in relative.parts
        metadata_path = cache / "upload" / (filename + ".metadata")
        metadata_path.parent.mkdir(parents=True, exist_ok=True)
        return _local_folder.LocalUploadFilePaths(
            path_in_repo=filename,
            file_path=release_root / relative,
            lock_path=metadata_path.with_suffix(".lock"),
            metadata_path=metadata_path,
        )

    def verified_metadata(local_dir, filename):
        result = original_metadata(local_dir, filename)
        row = indexed.get(filename)
        if row and result.sha256 is None:
            assert result.size == int(row["bytes"])
            result.sha256 = row["sha256"]
        return result

    def cached_operation(item):
        paths, metadata = item
        sample = samples.get(paths.path_in_repo)
        if sample is None:
            return original_operation(item)
        operation = _upload_large_folder.HackyCommitOperationAdd(
            path_in_repo=paths.path_in_repo,
            path_or_fileobj=cached_paths.get(paths.path_in_repo, paths.file_path),
        )
        operation.upload_info = _upload_large_folder.UploadInfo(
            sha256=bytes.fromhex(metadata.sha256), size=metadata.size, sample=sample,
        )
        operation._upload_mode = metadata.upload_mode
        operation._should_ignore = metadata.should_ignore
        operation._remote_oid = metadata.remote_oid
        return operation

    _local_folder._huggingface_dir = cache_directory
    _local_folder.get_local_upload_paths = upload_paths
    _upload_large_folder.get_local_upload_paths = upload_paths
    _upload_large_folder.read_upload_metadata = verified_metadata
    _upload_large_folder._build_hacky_operation = cached_operation
    _upload_large_folder.filter_repo_objects = selected_release_files
    Path.stat = snapshot_stat
    return {"payload_paths": cached_paths, "release_files": selected_names, "original_stat": original_stat}