Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / ml / upload_gemma4.py
upload_gemma4.py195 lines · 7.3 KiBRaw
| 1 | """Upload the Gemma 4 maml release set to R2 under models/gemma4/ and verify it over HTTPS. |
| 2 | |
| 3 | Usage: python scripts/ml/upload_gemma4.py <release-dir> |
| 4 | python scripts/ml/upload_gemma4.py --find-bucket |
| 5 | |
| 6 | <release-dir> holds the six FILES plus SHA256SUMS (`<sha256> <size> <name>` per line). The |
| 7 | bucket is the one that already serves https://data.maproj.org/models/, found by locating |
| 8 | LEGACY_KEY on each bucket the credentials can list (override with R2_MODELS_BUCKET). An object |
| 9 | that already exists with the same size and sha256 is skipped; one that differs is refused, so |
| 10 | nothing else on the bucket is overwritten. Nothing is ever deleted. |
| 11 | |
| 12 | After upload each file is checked through the CDN: HEAD returns 200 with the right |
| 13 | Content-Length, a Range request returns 206, and files up to VERIFY_FULL_BYTES are downloaded |
| 14 | whole and hashed. |
| 15 | |
| 16 | Required env (never put keys on the command line): |
| 17 | R2_ENDPOINT S3 API endpoint, e.g. https://<ACCOUNT_ID>.r2.cloudflarestorage.com |
| 18 | R2_ACCESS_KEY_ID R2 access key id |
| 19 | R2_SECRET_ACCESS_KEY R2 secret access key |
| 20 | Optional env: |
| 21 | R2_MODELS_BUCKET Skip the bucket search |
| 22 | R2_CDN Default: https://data.maproj.org |
| 23 | """ |
| 24 | import hashlib |
| 25 | import os |
| 26 | import sys |
| 27 | import threading |
| 28 | import urllib.request |
| 29 | |
| 30 | import boto3 |
| 31 | from boto3.s3.transfer import TransferConfig |
| 32 | from botocore.exceptions import ClientError |
| 33 | |
| 34 | FILES = [ |
| 35 | "gemma4_text.maml", |
| 36 | "gemma4_embed.maml", |
| 37 | "gemma4_head.maml", |
| 38 | "gemma4_vision.maml", |
| 39 | "gemma4_audio.maml", |
| 40 | "gemma4_tokenizer.spm1", |
| 41 | ] |
| 42 | PREFIX = "models/gemma4/" |
| 43 | LEGACY_KEY = "models/gemma-4-E2B-it.litertlm" |
| 44 | CDN = os.environ.get("R2_CDN", "https://data.maproj.org") |
| 45 | PART_SIZE = 100 * 1024 * 1024 |
| 46 | VERIFY_FULL_BYTES = 500 * 1024 * 1024 |
| 47 | # The CDN answers Python-urllib's default User-Agent with 403. |
| 48 | USER_AGENT = {"User-Agent": "modern-apps-upload-gemma4/1"} |
| 49 | |
| 50 | |
| 51 | def client(): |
| 52 | missing = [v for v in ("R2_ENDPOINT", "R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY") |
| 53 | if not os.environ.get(v)] |
| 54 | if missing: |
| 55 | raise SystemExit(f"missing env: {', '.join(missing)} (see module docstring)") |
| 56 | return boto3.client( |
| 57 | "s3", |
| 58 | endpoint_url=os.environ["R2_ENDPOINT"], |
| 59 | aws_access_key_id=os.environ["R2_ACCESS_KEY_ID"], |
| 60 | aws_secret_access_key=os.environ["R2_SECRET_ACCESS_KEY"], |
| 61 | region_name="auto", |
| 62 | ) |
| 63 | |
| 64 | |
| 65 | def head(s3, bucket, key): |
| 66 | try: |
| 67 | return s3.head_object(Bucket=bucket, Key=key) |
| 68 | except ClientError as e: |
| 69 | if e.response.get("Error", {}).get("Code") in ("404", "NoSuchKey", "NotFound"): |
| 70 | return None |
| 71 | raise |
| 72 | |
| 73 | |
| 74 | def find_bucket(s3): |
| 75 | pinned = os.environ.get("R2_MODELS_BUCKET") |
| 76 | if pinned: |
| 77 | if head(s3, pinned, LEGACY_KEY) is None: |
| 78 | raise SystemExit(f"R2_MODELS_BUCKET={pinned} holds no {LEGACY_KEY}") |
| 79 | return pinned |
| 80 | names = [b["Name"] for b in s3.list_buckets().get("Buckets", [])] |
| 81 | found = [] |
| 82 | for name in names: |
| 83 | try: |
| 84 | meta = head(s3, name, LEGACY_KEY) |
| 85 | except ClientError as e: |
| 86 | print(f" {name}: {e.response.get('Error', {}).get('Code')}", flush=True) |
| 87 | continue |
| 88 | print(f" {name}: {'has' if meta else 'no'} {LEGACY_KEY}" |
| 89 | + (f" ({meta['ContentLength']} bytes)" if meta else ""), flush=True) |
| 90 | if meta: |
| 91 | found.append(name) |
| 92 | if len(found) != 1: |
| 93 | raise SystemExit(f"{len(found)} buckets hold {LEGACY_KEY} ({found}); set R2_MODELS_BUCKET") |
| 94 | return found[0] |
| 95 | |
| 96 | |
| 97 | def read_sums(release): |
| 98 | sums = {} |
| 99 | with open(os.path.join(release, "SHA256SUMS")) as f: |
| 100 | for line in f: |
| 101 | digest, size, name = line.split() |
| 102 | sums[name] = (digest, int(size)) |
| 103 | missing = [n for n in FILES if n not in sums] |
| 104 | if missing: |
| 105 | raise SystemExit(f"SHA256SUMS lacks {missing}") |
| 106 | return sums |
| 107 | |
| 108 | |
| 109 | def sha256_file(path): |
| 110 | h = hashlib.sha256() |
| 111 | with open(path, "rb") as f: |
| 112 | while chunk := f.read(1 << 20): |
| 113 | h.update(chunk) |
| 114 | return h.hexdigest() |
| 115 | |
| 116 | |
| 117 | def upload(s3, bucket, release, sums): |
| 118 | config = TransferConfig(multipart_threshold=PART_SIZE, multipart_chunksize=PART_SIZE, |
| 119 | max_concurrency=10, use_threads=True) |
| 120 | for name in FILES: |
| 121 | local = os.path.join(release, name) |
| 122 | digest, size = sums[name] |
| 123 | if os.path.getsize(local) != size: |
| 124 | raise SystemExit(f"{local}: {os.path.getsize(local)} bytes, SHA256SUMS says {size}") |
| 125 | key = PREFIX + name |
| 126 | existing = head(s3, bucket, key) |
| 127 | if existing is not None: |
| 128 | same = (existing["ContentLength"] == size |
| 129 | and existing.get("Metadata", {}).get("sha256") == digest) |
| 130 | if same: |
| 131 | print(f"skip {key}: already {size} bytes, sha256 {digest}", flush=True) |
| 132 | continue |
| 133 | raise SystemExit(f"{key} exists with different content; refusing to overwrite") |
| 134 | print(f"uploading {local} ({size / 1e6:.1f} MB) to s3://{bucket}/{key}", flush=True) |
| 135 | lock, done, mark = threading.Lock(), [0], [0.0] |
| 136 | |
| 137 | def progress(n, size=size): |
| 138 | with lock: |
| 139 | done[0] += n |
| 140 | if done[0] - mark[0] >= 5e8 or done[0] >= size: |
| 141 | mark[0] = done[0] |
| 142 | print(f" {done[0] / 1e6:.0f}/{size / 1e6:.0f} MB", flush=True) |
| 143 | |
| 144 | s3.upload_file(local, bucket, key, Config=config, Callback=progress, |
| 145 | ExtraArgs={"ContentType": "application/octet-stream", |
| 146 | "Metadata": {"sha256": digest}}) |
| 147 | remote = s3.head_object(Bucket=bucket, Key=key)["ContentLength"] |
| 148 | if remote != size: |
| 149 | raise SystemExit(f"{key}: remote {remote} bytes, local {size}") |
| 150 | |
| 151 | |
| 152 | def verify_https(sums): |
| 153 | ok = True |
| 154 | for name in FILES: |
| 155 | digest, size = sums[name] |
| 156 | url = f"{CDN}/{PREFIX}{name}" |
| 157 | with urllib.request.urlopen(urllib.request.Request(url, method="HEAD", headers=USER_AGENT)) as r: |
| 158 | length = int(r.headers.get("Content-Length", -1)) |
| 159 | head_ok = r.status == 200 and length == size |
| 160 | ranged = urllib.request.Request(url, headers={**USER_AGENT, "Range": "bytes=0-15"}) |
| 161 | with urllib.request.urlopen(ranged) as r: |
| 162 | body = r.read() |
| 163 | range_ok = r.status == 206 and len(body) == 16 |
| 164 | full = "skipped (large)" |
| 165 | if size <= VERIFY_FULL_BYTES: |
| 166 | h = hashlib.sha256() |
| 167 | with urllib.request.urlopen(urllib.request.Request(url, headers=USER_AGENT)) as r: |
| 168 | while chunk := r.read(1 << 20): |
| 169 | h.update(chunk) |
| 170 | full = "sha256 ok" if h.hexdigest() == digest else f"SHA256 MISMATCH {h.hexdigest()}" |
| 171 | ok &= h.hexdigest() == digest |
| 172 | ok &= head_ok and range_ok |
| 173 | print(f"{url}: HEAD {'ok' if head_ok else f'BAD ({length})'}, " |
| 174 | f"range {'206' if range_ok else 'BAD'}, {full}", flush=True) |
| 175 | return ok |
| 176 | |
| 177 | |
| 178 | def main(): |
| 179 | if len(sys.argv) == 2 and sys.argv[1] == "--find-bucket": |
| 180 | print(find_bucket(client()), flush=True) |
| 181 | return 0 |
| 182 | if len(sys.argv) != 2: |
| 183 | print(__doc__.splitlines()[2], flush=True) |
| 184 | return 2 |
| 185 | release = sys.argv[1] |
| 186 | sums = read_sums(release) |
| 187 | s3 = client() |
| 188 | bucket = find_bucket(s3) |
| 189 | print(f"bucket {bucket} serves {CDN}/models/", flush=True) |
| 190 | upload(s3, bucket, release, sums) |
| 191 | return 0 if verify_https(sums) else 1 |
| 192 | |
| 193 | |
| 194 | if __name__ == "__main__": |
| 195 | sys.exit(main()) |