Spaces:
Running on Zero
Running on Zero
File size: 11,228 Bytes
0a96270 | 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 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 | # SPDX-License-Identifier: Apache-2.0
"""Offline request-limit errors and the GPU-allocation boundary."""
from __future__ import annotations
import importlib
import sys
import types
import json
import tempfile
from pathlib import Path
import unittest
from dataclasses import replace
from unittest.mock import patch
from scripts.config import LIMITS, MODEL_REGISTRY
from scripts.errors import RequestError, gpu_failure
from scripts.requests import parse_job
from scripts.usage import UsageStore
def payload(*lengths):
return {"sequences": [{"id": f"r{i}", "sequence": "A" * n} for i, n in enumerate(lengths)]}
class ErrorTests(unittest.TestCase):
def check_limit(self, task, body, limits, code, message):
with self.assertRaises(RequestError) as ctx:
parse_job(task, body, limits)
self.assertEqual(ctx.exception.code, code)
self.assertIn(message, str(ctx.exception))
def test_independent_limits(self):
cases = [
("embed", payload(4, 5), replace(LIMITS, max_records=1), "max_records", "2 sequences"),
("embed", payload(4, 5), replace(LIMITS, max_total_nt=8), "max_total_nt", "8 total nucleotides"),
("embed", payload(10241), LIMITS, "native_context", "10,240 nt"),
("embed", payload(4, 5), replace(LIMITS, max_forward_tokens=12), "max_forward_tokens", "13 forward tokens"),
("embed", payload(4, 5), replace(LIMITS, max_attention_cells=84), "max_attention_cells", "85 cells"),
("embed", payload(*([10240] * 9)), replace(LIMITS, max_attention_cells=8*10242**2), "max_attention_cells", "944,087,076 cells"),
]
for task, body, limits, code, phrase in cases:
with self.subTest(code=code):
self.check_limit(task, body, limits, code, phrase)
def test_variant_counts(self):
body = {"sequences": [{"id": "r", "sequence": "A" * 1024, "variants": ["A1C", "A1G", "A1U", "A2G"]}]}
self.assertEqual(parse_job("variant", body, replace(LIMITS, max_mask_patterns=2)).forward_lengths, (1024, 1024))
self.check_limit("variant", body, replace(LIMITS, max_variants=3), "max_variants", "3 variants")
self.check_limit("variant", body, replace(LIMITS, max_mask_patterns=1), "max_mask_patterns", "2 distinct mask patterns")
long_body = {"sequences": [{"id": "r", "sequence": "A" * 12000, "variants": ["A1G,A12000C"]}]}
self.check_limit("variant", long_body, LIMITS, "variant_span", "12,000 nt")
full = {"sequences": [{"id": "r", "sequence": "A" * 1024, "variants": [f"A{i}G" for i in range(1, 129)]}]}
self.check_limit("variant", full, replace(LIMITS,max_forward_tokens=131072), "max_forward_tokens", "131,328 forward tokens")
def test_duration_and_output_limits(self):
from scripts.requests import estimate_duration
job = parse_job("embed", payload(*([10240] * 7)))
self.assertLessEqual(job.estimated_seconds, LIMITS.max_gpu_seconds)
self.assertEqual(estimate_duration("embed", payload(*([10240] * 7))), job.estimated_seconds)
self.check_limit("embed", payload(*([10240] * 8)), LIMITS, "max_gpu_duration", "131 s")
self.check_limit("fill", {"sequences": [{"id": "r", "sequence": "NN", "positions": [0,1]}]},
replace(LIMITS, max_masked_sites=1), "max_masked_sites", "1 masked sites")
self.check_limit("variant", {"sequences": [{"id": "r", "sequence": "A", "variants": ["A1C"]}]},
replace(LIMITS, max_variant_chars=2), "max_variant_chars", "2 characters")
job = parse_job("variant", {"sequences": [{"id": "r", "sequence":"A"*1000000, "variants":["A500000G"]}]})
self.assertEqual(job.forward_lengths, (10240,))
self.assertEqual(job.records[0].variants[0].end-job.records[0].variants[0].start, 10240)
def test_platform_classification(self):
for message, code in [
("ZeroGPU quota exceeded (60s requested vs 20s left)", "gpu_quota"),
("You have exceeded your ZeroGPU runs limit. Authenticate with a Hugging Face token for more quota.", "gpu_runs_limit"),
("You have exceeded your runs limit. Authenticate with a Hugging Face token for more quota.", "gpu_runs_limit"),
("You have exceeded your GPU quota (60s requested vs 20s left)", "gpu_quota"),
("You have exceeded your Pro GPU quota", "gpu_quota"),
("GPU quota exhausted", "gpu_quota"),
("Out of ZeroGPU quota", "gpu_quota"),
("The requested GPU duration (120s) is larger than the maximum allowed", "gpu_duration_limit"),
("ZeroGPU illegal duration", "gpu_duration_limit"),
("Queue is full. Please try again.", "queue_full"),
("CUDA out of memory. internal detail", "gpu_memory"),
("GPU task timed out", "gpu_timeout"),
]:
with self.subTest(code=code):
self.assertEqual(gpu_failure(message)[0], code)
self.assertNotIn("internal detail", gpu_failure(message)[1])
self.assertEqual(gpu_failure("You have exceeded your runs limit.", "ZeroGPU quota exceeded")[0], "gpu_runs_limit")
self.assertIsNone(gpu_failure("unrelated exception in model code"))
self.assertIsNone(gpu_failure("Disk storage quota exceeded"))
self.assertEqual(gpu_failure("CUDA out of memory", "ZeroGPU quota exceeded")[0], "gpu_memory")
def test_app_wrappers_before_gpu(self):
allocations = []
def gpu(**kwargs):
def decorate(fn):
def wrapped(*args):
allocations.append(fn.__name__)
return fn(*args)
return wrapped
return decorate
class Component:
def __init__(self, *args, **kwargs):
pass
def __enter__(self):
return self
def __exit__(self, *args):
pass
def click(self, *args, **kwargs):
pass
def queue(self, **kwargs):
return self
gr = types.ModuleType("gradio")
for name in ("Blocks", "Markdown", "Tab", "Code", "JSON", "Button", "File"):
setattr(gr, name, Component)
mock_spaces = types.SimpleNamespace(GPU=gpu)
oom = type("OutOfMemoryError", (RuntimeError,), {})
mock_torch = types.SimpleNamespace(device=lambda name: name, cuda=types.SimpleNamespace(
is_available=lambda: False, OutOfMemoryError=oom))
mock_inference = types.SimpleNamespace(ensure_embedding_capacity=lambda job: None, embed_job=lambda job, models: ({"results": []}, ["matrix.npz"]),
fill_job=lambda job, models: {"results": []})
mock_score = types.SimpleNamespace(score_job=lambda job, models: {"results": []})
mock_model = types.SimpleNamespace(load_registry=lambda device: MODEL_REGISTRY)
modules = {"spaces": mock_spaces, "gradio": gr, "torch": mock_torch,
"scripts.inference": mock_inference, "scripts.score": mock_score, "scripts.model_io": mock_model}
try:
with patch.dict(sys.modules, modules), tempfile.TemporaryDirectory() as directory:
app = importlib.import_module("app")
app.USAGE = UsageStore(directory)
result, files = app.embed(payload(10241))
self.assertEqual(result["error"]["code"], "native_context")
self.assertEqual(files, [])
self.assertEqual(app.fill("not JSON")["error"]["code"], "invalid_request")
self.assertEqual(app.variant({"sequences": []})["error"]["code"], "invalid_request")
self.assertEqual(allocations, [])
with patch.object(app, "ensure_embedding_capacity", side_effect=RequestError("output_storage", "Storage full.")):
result, files = app.embed(payload(6))
self.assertEqual(result["error"]["code"], "output_storage")
self.assertEqual(files, [])
self.assertEqual(allocations, [])
self.assertEqual(app.embed(payload(6)), ({"results": []}, ["matrix.npz"]))
self.assertEqual(allocations, ["_embed_gpu"])
with patch.object(app, "_embed_gpu", side_effect=RuntimeError("ZeroGPU quota exceeded")):
result, files = app.embed(payload(6))
self.assertEqual(result["error"]["code"], "gpu_quota")
self.assertEqual(files, [])
class RunLimitError(Exception):
title = "ZeroGPU quota exceeded"
message = "You have exceeded your runs limit."
def __str__(self):
return "Private internal exception details"
with patch.object(app, "_embed_gpu", side_effect=RunLimitError()):
result, files = app.embed(payload(6))
self.assertEqual(result["error"]["code"], "gpu_runs_limit")
self.assertNotIn("Private internal", result["error"]["message"])
self.assertEqual(files, [])
with patch.object(app, "_fill_gpu", side_effect=RunLimitError()):
result = app.fill({"sequences":[{"id":"r","sequence":"AN","positions":[1]}]})
self.assertEqual(result["error"]["code"],"gpu_runs_limit")
with patch.object(app, "_variant_gpu", side_effect=RunLimitError()):
result = app.variant({"sequences":[{"id":"r","sequence":"A","variants":["A1G"]}]})
self.assertEqual(result["error"]["code"],"gpu_runs_limit")
with patch.object(app, "_embed_gpu", side_effect=oom("internal details")):
result, files = app.embed(payload(6))
self.assertEqual(result["error"]["code"], "gpu_memory")
self.assertNotIn("internal details", result["error"]["message"])
with patch.object(app, "_embed_gpu", side_effect=RuntimeError("private internal failure")):
with self.assertRaises(RuntimeError):
app.embed(payload(6))
files=list(Path(directory).glob("*.json"))
self.assertEqual(len(files),1)
totals=json.loads(files[0].read_text())["totals"]
self.assertEqual(totals["requests"],11)
self.assertEqual((totals["succeeded"],totals["rejected"],totals["failed"]),(1,4,6))
self.assertEqual(totals["gpu_calls_attempted"],7)
self.assertEqual(totals["errors"]["gpu_runs_limit"],3)
self.assertEqual(totals["measured_successful_batches"],1)
# Saving statistics is best-effort; errors cannot replace the API response.
with patch.object(app.USAGE, "_save", side_effect=OSError("storage unavailable")):
self.assertEqual(app.embed(payload(6)), ({"results": []}, ["matrix.npz"]))
finally:
sys.modules.pop("app", None)
if __name__ == "__main__":
unittest.main()
|