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
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
Gemma-based hint generation entrypoint.
|
| 6 |
+
|
| 7 |
+
This is a dedicated wrapper around `hintgenerate.py` with Gemma-local defaults.
|
| 8 |
+
It keeps the same processing pipeline and most CLI flags, but changes:
|
| 9 |
+
|
| 10 |
+
1. default `--model-name` to the provided Gemma checkpoint
|
| 11 |
+
2. local HF loader preference for Gemma-family models
|
| 12 |
+
3. default `--workers` to 1 for local inference stability
|
| 13 |
+
|
| 14 |
+
Example:
|
| 15 |
+
|
| 16 |
+
python3 hintgenerate_gemma.py \
|
| 17 |
+
--use-json \
|
| 18 |
+
--json-path /path/to/editing.json \
|
| 19 |
+
--image-root /path/to/images \
|
| 20 |
+
--out-root ./gemma_hint_runs \
|
| 21 |
+
--grid-mode auto \
|
| 22 |
+
--model-max-tokens 4096
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
import argparse
|
| 26 |
+
import inspect
|
| 27 |
+
import os
|
| 28 |
+
import sys
|
| 29 |
+
from typing import Any, Dict, List, Optional
|
| 30 |
+
|
| 31 |
+
from hintgenerate import (
|
| 32 |
+
GATEWAY_BASE_URL,
|
| 33 |
+
DEFAULT_TIMEOUT,
|
| 34 |
+
MAX_RETRIES_ENV,
|
| 35 |
+
GeminiGatewayClient,
|
| 36 |
+
KeyedRateLimiter,
|
| 37 |
+
_patch_bitsandbytes_compat,
|
| 38 |
+
_patch_torch_distributed_tensor_compat,
|
| 39 |
+
_patch_torch_module_compat,
|
| 40 |
+
assert_local_openai_server_ready,
|
| 41 |
+
is_local_model_name,
|
| 42 |
+
is_local_openai_base_url,
|
| 43 |
+
logger,
|
| 44 |
+
resolve_model_name,
|
| 45 |
+
run_json_mode,
|
| 46 |
+
run_parquet_mode,
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
GEMMA_MODEL_PATH = "/mnt/bn/yuanpengtu/svgthink/google/gemma-4-31B-it/"
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class GemmaHintClient(GeminiGatewayClient):
|
| 54 |
+
"""
|
| 55 |
+
Official Gemma 4 local loader.
|
| 56 |
+
|
| 57 |
+
Per the official Hugging Face Gemma 4 docs:
|
| 58 |
+
- processor: AutoProcessor / Gemma4Processor
|
| 59 |
+
- multimodal model: AutoModelForMultimodalLM
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
def __init__(self, *args, local_processor_path: str = "", local_processor_class: str = "", **kwargs):
|
| 63 |
+
self.local_processor_path = str(local_processor_path or "").strip()
|
| 64 |
+
self.local_processor_class = str(local_processor_class or "").strip()
|
| 65 |
+
self.local_device_map = str(kwargs.pop("local_device_map", "auto") or "auto").strip()
|
| 66 |
+
self.local_max_memory_per_gpu_gb = kwargs.pop("local_max_memory_per_gpu_gb", None)
|
| 67 |
+
|
| 68 |
+
sig = inspect.signature(GeminiGatewayClient.__init__)
|
| 69 |
+
allowed = set(sig.parameters.keys()) - {"self"}
|
| 70 |
+
filtered_kwargs = {k: v for k, v in kwargs.items() if k in allowed}
|
| 71 |
+
super().__init__(*args, **filtered_kwargs)
|
| 72 |
+
|
| 73 |
+
# Old hintgenerate.py may not know these attributes.
|
| 74 |
+
self.local_processor_path = str(local_processor_path or getattr(self, "local_processor_path", "")).strip()
|
| 75 |
+
self.local_processor_class = str(local_processor_class or getattr(self, "local_processor_class", "")).strip()
|
| 76 |
+
|
| 77 |
+
def _select_local_loader_candidates(self, transformers_mod):
|
| 78 |
+
auto_multimodal = getattr(transformers_mod, "AutoModelForMultimodalLM", None)
|
| 79 |
+
gemma4_cond = getattr(transformers_mod, "Gemma4ForConditionalGeneration", None)
|
| 80 |
+
auto_image_text = getattr(transformers_mod, "AutoModelForImageTextToText", None)
|
| 81 |
+
auto_vision2seq = getattr(transformers_mod, "AutoModelForVision2Seq", None)
|
| 82 |
+
auto_causal_lm = getattr(transformers_mod, "AutoModelForCausalLM", None)
|
| 83 |
+
auto_model = getattr(transformers_mod, "AutoModel", None)
|
| 84 |
+
|
| 85 |
+
return [
|
| 86 |
+
loader
|
| 87 |
+
for loader in (
|
| 88 |
+
auto_multimodal,
|
| 89 |
+
gemma4_cond,
|
| 90 |
+
auto_image_text,
|
| 91 |
+
auto_vision2seq,
|
| 92 |
+
auto_causal_lm,
|
| 93 |
+
auto_model,
|
| 94 |
+
)
|
| 95 |
+
if loader is not None
|
| 96 |
+
]
|
| 97 |
+
|
| 98 |
+
def _get_local_processor_candidates(self, transformers_mod):
|
| 99 |
+
proc_path = self.local_processor_path or self.model
|
| 100 |
+
candidates = []
|
| 101 |
+
seen = set()
|
| 102 |
+
|
| 103 |
+
def _push(name: str):
|
| 104 |
+
if not name or name in seen:
|
| 105 |
+
return
|
| 106 |
+
klass = getattr(transformers_mod, name, None)
|
| 107 |
+
if klass is not None:
|
| 108 |
+
candidates.append((name, klass, proc_path))
|
| 109 |
+
seen.add(name)
|
| 110 |
+
|
| 111 |
+
if self.local_processor_class:
|
| 112 |
+
_push(self.local_processor_class)
|
| 113 |
+
|
| 114 |
+
for name in ("Gemma4Processor", "AutoProcessor"):
|
| 115 |
+
_push(name)
|
| 116 |
+
|
| 117 |
+
if candidates:
|
| 118 |
+
return candidates
|
| 119 |
+
return super()._get_local_processor_candidates(transformers_mod)
|
| 120 |
+
|
| 121 |
+
@staticmethod
|
| 122 |
+
def _load_from_pretrained(factory, path: str, trust_remote_code: bool = True, use_fast: Optional[bool] = None):
|
| 123 |
+
kwargs: Dict[str, Any] = {}
|
| 124 |
+
if trust_remote_code:
|
| 125 |
+
kwargs["trust_remote_code"] = True
|
| 126 |
+
if use_fast is not None:
|
| 127 |
+
kwargs["use_fast"] = use_fast
|
| 128 |
+
|
| 129 |
+
try:
|
| 130 |
+
return factory.from_pretrained(path, **kwargs)
|
| 131 |
+
except TypeError:
|
| 132 |
+
kwargs.pop("use_fast", None)
|
| 133 |
+
try:
|
| 134 |
+
return factory.from_pretrained(path, **kwargs)
|
| 135 |
+
except TypeError:
|
| 136 |
+
kwargs.pop("trust_remote_code", None)
|
| 137 |
+
return factory.from_pretrained(path, **kwargs)
|
| 138 |
+
|
| 139 |
+
def _load_local_processor(self, transformers_mod):
|
| 140 |
+
tried = []
|
| 141 |
+
for label, factory, path in self._get_local_processor_candidates(transformers_mod):
|
| 142 |
+
if factory is None or not path:
|
| 143 |
+
continue
|
| 144 |
+
try:
|
| 145 |
+
proc = self._load_from_pretrained(factory, path, trust_remote_code=True, use_fast=None)
|
| 146 |
+
logger.info(f"Loaded local processor via {label}: path={path}")
|
| 147 |
+
return proc
|
| 148 |
+
except Exception as e:
|
| 149 |
+
tried.append(f"{label}@{path}: {e}")
|
| 150 |
+
|
| 151 |
+
dir_snaps = []
|
| 152 |
+
seen_paths = []
|
| 153 |
+
for _, _, path in self._get_local_processor_candidates(transformers_mod):
|
| 154 |
+
if not path or path in seen_paths or not os.path.isdir(path):
|
| 155 |
+
continue
|
| 156 |
+
seen_paths.append(path)
|
| 157 |
+
try:
|
| 158 |
+
names = sorted(os.listdir(path))
|
| 159 |
+
if len(names) > 24:
|
| 160 |
+
names = names[:24] + ["..."]
|
| 161 |
+
dir_snaps.append(f"{path}: {names}")
|
| 162 |
+
except Exception:
|
| 163 |
+
continue
|
| 164 |
+
|
| 165 |
+
detail = "\n".join(f"- {x}" for x in tried) if tried else "- no processor candidates available"
|
| 166 |
+
snapshot = ("\nDirectory snapshot:\n" + "\n".join(dir_snaps)) if dir_snaps else ""
|
| 167 |
+
raise RuntimeError(
|
| 168 |
+
"Failed to load a local processor for official Gemma 4 multimodal inference.\n"
|
| 169 |
+
f"Tried:\n{detail}{snapshot}\n"
|
| 170 |
+
"Use the official Gemma 4 path or model id (for example `google/gemma-4-31B-it`) "
|
| 171 |
+
"with a recent `transformers` version that provides `Gemma4Processor` and "
|
| 172 |
+
"`AutoModelForMultimodalLM`."
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
def _ensure_local_model_loaded(self):
|
| 176 |
+
if self._local_load_error is not None:
|
| 177 |
+
raise self._local_load_error
|
| 178 |
+
|
| 179 |
+
if self._local_model is not None and self._processor is not None:
|
| 180 |
+
return
|
| 181 |
+
|
| 182 |
+
with self._local_lock:
|
| 183 |
+
if self._local_load_error is not None:
|
| 184 |
+
raise self._local_load_error
|
| 185 |
+
if self._local_model is not None and self._processor is not None:
|
| 186 |
+
return
|
| 187 |
+
|
| 188 |
+
try:
|
| 189 |
+
import torch
|
| 190 |
+
import transformers
|
| 191 |
+
except Exception as e:
|
| 192 |
+
raise RuntimeError(
|
| 193 |
+
"Local model mode requires torch and transformers to be installed in this environment."
|
| 194 |
+
) from e
|
| 195 |
+
|
| 196 |
+
self._torch = torch
|
| 197 |
+
_patch_torch_module_compat(torch)
|
| 198 |
+
_patch_torch_distributed_tensor_compat(torch)
|
| 199 |
+
|
| 200 |
+
if getattr(transformers, "Gemma4Processor", None) is None and getattr(transformers, "AutoProcessor", None) is None:
|
| 201 |
+
raise RuntimeError(
|
| 202 |
+
"This transformers build does not provide Gemma4Processor/AutoProcessor for Gemma 4. "
|
| 203 |
+
"Upgrade transformers to a version with official Gemma 4 support."
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
loader_candidates = self._select_local_loader_candidates(transformers)
|
| 207 |
+
if not loader_candidates:
|
| 208 |
+
version = getattr(transformers, "__version__", "unknown")
|
| 209 |
+
raise RuntimeError(
|
| 210 |
+
"This transformers build does not provide any usable Gemma 4 model loader "
|
| 211 |
+
f"(checked AutoModelForMultimodalLM, Gemma4ForConditionalGeneration, "
|
| 212 |
+
f"AutoModelForImageTextToText, AutoModelForVision2Seq, AutoModelForCausalLM, AutoModel). "
|
| 213 |
+
f"Current transformers version: {version}. "
|
| 214 |
+
"Upgrade transformers to a version with official Gemma 4 support."
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
bits_and_bytes_config = getattr(transformers, "BitsAndBytesConfig", None)
|
| 218 |
+
|
| 219 |
+
model_kwargs: Dict[str, Any] = {
|
| 220 |
+
"trust_remote_code": True,
|
| 221 |
+
"device_map": self.local_device_map or "auto",
|
| 222 |
+
"low_cpu_mem_usage": True,
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
if self.local_max_memory_per_gpu_gb:
|
| 226 |
+
try:
|
| 227 |
+
gpu_count = int(torch.cuda.device_count())
|
| 228 |
+
except Exception:
|
| 229 |
+
gpu_count = 0
|
| 230 |
+
if gpu_count > 0:
|
| 231 |
+
per_gpu = f"{int(self.local_max_memory_per_gpu_gb)}GiB"
|
| 232 |
+
model_kwargs["max_memory"] = {idx: per_gpu for idx in range(gpu_count)}
|
| 233 |
+
model_kwargs["max_memory"]["cpu"] = "256GiB"
|
| 234 |
+
|
| 235 |
+
torch_dtype = self._resolve_local_torch_dtype(torch)
|
| 236 |
+
if torch_dtype is not None:
|
| 237 |
+
model_kwargs["dtype"] = torch_dtype
|
| 238 |
+
|
| 239 |
+
if self.local_load_in_4bit or self.local_load_in_8bit:
|
| 240 |
+
_patch_bitsandbytes_compat()
|
| 241 |
+
if bits_and_bytes_config is None:
|
| 242 |
+
raise RuntimeError("bitsandbytes support requires a recent transformers installation.")
|
| 243 |
+
quant_kwargs = {
|
| 244 |
+
"load_in_4bit": self.local_load_in_4bit,
|
| 245 |
+
"load_in_8bit": self.local_load_in_8bit,
|
| 246 |
+
}
|
| 247 |
+
if self.local_cpu_offload:
|
| 248 |
+
quant_kwargs["llm_int8_enable_fp32_cpu_offload"] = True
|
| 249 |
+
if self.local_load_in_4bit:
|
| 250 |
+
quant_kwargs["bnb_4bit_compute_dtype"] = torch_dtype or torch.bfloat16
|
| 251 |
+
quant_kwargs["bnb_4bit_quant_type"] = "nf4"
|
| 252 |
+
quant_kwargs["bnb_4bit_use_double_quant"] = True
|
| 253 |
+
model_kwargs["quantization_config"] = bits_and_bytes_config(**quant_kwargs)
|
| 254 |
+
model_kwargs.pop("dtype", None)
|
| 255 |
+
if self.local_cpu_offload:
|
| 256 |
+
offload_dir = self.local_offload_dir or os.path.join(os.getcwd(), ".hf_offload")
|
| 257 |
+
os.makedirs(offload_dir, exist_ok=True)
|
| 258 |
+
model_kwargs["offload_folder"] = offload_dir
|
| 259 |
+
model_kwargs["offload_state_dict"] = True
|
| 260 |
+
|
| 261 |
+
self._processor = self._load_local_processor(transformers)
|
| 262 |
+
|
| 263 |
+
last_err = None
|
| 264 |
+
loader_names = [getattr(loader, "__name__", str(loader)) for loader in loader_candidates]
|
| 265 |
+
logger.info(f"Local loader order: {loader_names}")
|
| 266 |
+
for loader in loader_candidates:
|
| 267 |
+
if loader is None:
|
| 268 |
+
continue
|
| 269 |
+
try:
|
| 270 |
+
self._local_model = loader.from_pretrained(self.model, **model_kwargs)
|
| 271 |
+
break
|
| 272 |
+
except Exception as e:
|
| 273 |
+
last_err = e
|
| 274 |
+
|
| 275 |
+
if self._local_model is None:
|
| 276 |
+
self._local_load_error = last_err or RuntimeError("unknown local model load error")
|
| 277 |
+
raise RuntimeError(f"Failed to load local model from {self.model}: {last_err}") from last_err
|
| 278 |
+
|
| 279 |
+
self._local_model.eval()
|
| 280 |
+
self._local_load_error = None
|
| 281 |
+
|
| 282 |
+
if hasattr(self._local_model, "hf_device_map"):
|
| 283 |
+
for dev in self._local_model.hf_device_map.values():
|
| 284 |
+
if dev not in ("cpu", "disk", "meta"):
|
| 285 |
+
if isinstance(dev, int):
|
| 286 |
+
dev = f"cuda:{dev}"
|
| 287 |
+
self._local_input_device = dev
|
| 288 |
+
break
|
| 289 |
+
|
| 290 |
+
if self._local_input_device is None:
|
| 291 |
+
model_device = getattr(self._local_model, "device", None)
|
| 292 |
+
if model_device is not None:
|
| 293 |
+
if isinstance(model_device, int):
|
| 294 |
+
model_device = f"cuda:{model_device}"
|
| 295 |
+
self._local_input_device = model_device
|
| 296 |
+
|
| 297 |
+
gpu_count = 0
|
| 298 |
+
try:
|
| 299 |
+
gpu_count = int(torch.cuda.device_count())
|
| 300 |
+
except Exception:
|
| 301 |
+
gpu_count = 0
|
| 302 |
+
logger.info(
|
| 303 |
+
f"Loaded local HF model: model={self.model} "
|
| 304 |
+
f"dtype={self.local_dtype} 4bit={self.local_load_in_4bit} 8bit={self.local_load_in_8bit} "
|
| 305 |
+
f"device_map={self.local_device_map or 'auto'} visible_gpus={gpu_count} "
|
| 306 |
+
f"cpu_offload={self.local_cpu_offload} offload_dir={self.local_offload_dir or 'auto'}"
|
| 307 |
+
)
|
| 308 |
+
if hasattr(self._local_model, "hf_device_map"):
|
| 309 |
+
logger.info(f"HF device map: {self._local_model.hf_device_map}")
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def build_parser() -> argparse.ArgumentParser:
|
| 313 |
+
parser = argparse.ArgumentParser()
|
| 314 |
+
|
| 315 |
+
parser.add_argument("--use-json", action="store_true")
|
| 316 |
+
parser.add_argument("--json-path", default="", help="Path to editing.json")
|
| 317 |
+
parser.add_argument("--image-root", default="", help="Root for json images")
|
| 318 |
+
parser.add_argument("--data-dir", default="", help="Dir with parquets")
|
| 319 |
+
parser.add_argument(
|
| 320 |
+
"--base-url",
|
| 321 |
+
default=GATEWAY_BASE_URL,
|
| 322 |
+
help="OpenAI-compatible API base URL for remote gateways or local /v1 servers.",
|
| 323 |
+
)
|
| 324 |
+
parser.add_argument(
|
| 325 |
+
"--force-api",
|
| 326 |
+
action="store_true",
|
| 327 |
+
help="Treat --model-name as an API model id even if it looks like a local path.",
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
parser.add_argument("--out-root", default="./gemma_hint_runs")
|
| 331 |
+
parser.add_argument("--max-side-start", type=int, default=480)
|
| 332 |
+
parser.add_argument("--limit-rows", type=int, default=None)
|
| 333 |
+
parser.add_argument("--rpm", type=int, default=1200)
|
| 334 |
+
parser.add_argument("--workers", type=int, default=1)
|
| 335 |
+
parser.add_argument("--grid-mode", default="auto", choices=["auto", "off"])
|
| 336 |
+
parser.add_argument("--grid-cell", type=int, default=64)
|
| 337 |
+
|
| 338 |
+
parser.add_argument("--stroke-width", type=int, default=6)
|
| 339 |
+
parser.add_argument("--label-scale", type=float, default=0.050)
|
| 340 |
+
|
| 341 |
+
parser.add_argument("--roi-topk", type=int, default=5)
|
| 342 |
+
parser.add_argument("--model-max-tokens", type=int, default=4096)
|
| 343 |
+
|
| 344 |
+
parser.add_argument("--verify", action="store_true")
|
| 345 |
+
parser.add_argument("--verify-threshold", type=float, default=0.3)
|
| 346 |
+
|
| 347 |
+
parser.add_argument("--log-missing", action="store_true")
|
| 348 |
+
|
| 349 |
+
parser.add_argument(
|
| 350 |
+
"--model-name",
|
| 351 |
+
default=os.environ.get("GEMMA_HINT_MODEL", GEMMA_MODEL_PATH),
|
| 352 |
+
help="Gemma checkpoint path or remote model id.",
|
| 353 |
+
)
|
| 354 |
+
parser.add_argument(
|
| 355 |
+
"--local-model-dtype",
|
| 356 |
+
default=os.environ.get("LOCAL_MODEL_DTYPE", "bfloat16"),
|
| 357 |
+
help="Torch dtype for local HF loading: auto, bfloat16, float16, float32",
|
| 358 |
+
)
|
| 359 |
+
parser.add_argument("--local-load-in-4bit", action="store_true")
|
| 360 |
+
parser.add_argument("--local-load-in-8bit", action="store_true")
|
| 361 |
+
parser.add_argument("--local-offload-dir", default="")
|
| 362 |
+
parser.add_argument(
|
| 363 |
+
"--local-device-map",
|
| 364 |
+
default=os.environ.get("LOCAL_DEVICE_MAP", "auto"),
|
| 365 |
+
help="HF device_map for local model loading, e.g. auto, balanced, balanced_low_0, sequential.",
|
| 366 |
+
)
|
| 367 |
+
parser.add_argument(
|
| 368 |
+
"--local-max-memory-per-gpu-gb",
|
| 369 |
+
type=int,
|
| 370 |
+
default=None,
|
| 371 |
+
help="Optional per-GPU max memory budget in GiB when using multi-GPU sharding.",
|
| 372 |
+
)
|
| 373 |
+
parser.add_argument(
|
| 374 |
+
"--local-processor-path",
|
| 375 |
+
default=os.environ.get("GEMMA_HINT_PROCESSOR_PATH", ""),
|
| 376 |
+
help="Optional directory containing tokenizer/processor files if they are separate from model weights.",
|
| 377 |
+
)
|
| 378 |
+
parser.add_argument(
|
| 379 |
+
"--local-processor-class",
|
| 380 |
+
default=os.environ.get("GEMMA_HINT_PROCESSOR_CLASS", ""),
|
| 381 |
+
help="Optional explicit processor class name, e.g. Gemma3Processor or PaliGemmaProcessor.",
|
| 382 |
+
)
|
| 383 |
+
parser.add_argument("--temperature", type=float, default=0.2)
|
| 384 |
+
parser.add_argument("--no-stop", action="store_true")
|
| 385 |
+
|
| 386 |
+
parser.add_argument("--session", action="store_true")
|
| 387 |
+
parser.add_argument("--session-keep-turns", type=int, default=4)
|
| 388 |
+
|
| 389 |
+
parser.add_argument(
|
| 390 |
+
"--keys",
|
| 391 |
+
nargs="+",
|
| 392 |
+
default=[],
|
| 393 |
+
help="API keys for gateway usage. Ignored in local model mode.",
|
| 394 |
+
)
|
| 395 |
+
return parser
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def build_client_pool(args) -> List[GemmaHintClient]:
|
| 399 |
+
model_name = resolve_model_name(args.model_name)
|
| 400 |
+
use_local_model = is_local_model_name(model_name) and (not args.force_api)
|
| 401 |
+
use_local_openai_server = (not use_local_model) and is_local_openai_base_url(args.base_url)
|
| 402 |
+
|
| 403 |
+
if args.force_api and (args.local_load_in_4bit or args.local_load_in_8bit):
|
| 404 |
+
raise RuntimeError("--force-api cannot be used together with --local-load-in-4bit/--local-load-in-8bit")
|
| 405 |
+
if args.local_load_in_4bit and args.local_load_in_8bit:
|
| 406 |
+
raise RuntimeError("Use at most one of --local-load-in-4bit / --local-load-in-8bit")
|
| 407 |
+
if use_local_model and not os.path.isdir(model_name):
|
| 408 |
+
raise RuntimeError(f"Local model path does not exist or is not a directory: {model_name}")
|
| 409 |
+
if use_local_model and (args.local_load_in_4bit or args.local_load_in_8bit):
|
| 410 |
+
if not args.local_offload_dir:
|
| 411 |
+
args.local_offload_dir = os.path.join(args.out_root, "_hf_offload")
|
| 412 |
+
os.makedirs(args.local_offload_dir, exist_ok=True)
|
| 413 |
+
|
| 414 |
+
keys: List[str] = []
|
| 415 |
+
limiter: Optional[KeyedRateLimiter] = None
|
| 416 |
+
if not use_local_model:
|
| 417 |
+
keys = args.keys or []
|
| 418 |
+
if not keys:
|
| 419 |
+
env_keys = os.environ.get("GPT_KEYS", "").strip()
|
| 420 |
+
if env_keys:
|
| 421 |
+
keys = [k.strip() for k in env_keys.split(",") if k.strip()]
|
| 422 |
+
if not keys and not use_local_openai_server:
|
| 423 |
+
raise RuntimeError("No API keys provided. Use --keys or set GPT_KEYS.")
|
| 424 |
+
if keys:
|
| 425 |
+
limiter = KeyedRateLimiter(rpm_per_key=args.rpm, keys=keys)
|
| 426 |
+
elif use_local_openai_server:
|
| 427 |
+
logger.warning(f"Using local OpenAI-compatible server without API key: base_url={args.base_url}")
|
| 428 |
+
assert_local_openai_server_ready(args.base_url)
|
| 429 |
+
|
| 430 |
+
num_workers = int(max(1, args.workers))
|
| 431 |
+
if use_local_model and num_workers != 1:
|
| 432 |
+
logger.warning("Local Gemma backend detected; forcing workers=1.")
|
| 433 |
+
num_workers = 1
|
| 434 |
+
args.workers = 1
|
| 435 |
+
|
| 436 |
+
clients: List[GemmaHintClient] = []
|
| 437 |
+
for i in range(num_workers):
|
| 438 |
+
api_key = keys[i % len(keys)] if keys else ""
|
| 439 |
+
clients.append(
|
| 440 |
+
GemmaHintClient(
|
| 441 |
+
api_key=api_key,
|
| 442 |
+
limiter=limiter,
|
| 443 |
+
base_url=args.base_url,
|
| 444 |
+
model=model_name,
|
| 445 |
+
timeout=DEFAULT_TIMEOUT,
|
| 446 |
+
max_retries=MAX_RETRIES_ENV,
|
| 447 |
+
temperature=args.temperature,
|
| 448 |
+
local_dtype=args.local_model_dtype,
|
| 449 |
+
local_load_in_4bit=args.local_load_in_4bit,
|
| 450 |
+
local_load_in_8bit=args.local_load_in_8bit,
|
| 451 |
+
local_cpu_offload=(args.local_load_in_4bit or args.local_load_in_8bit),
|
| 452 |
+
local_offload_dir=args.local_offload_dir,
|
| 453 |
+
local_device_map=args.local_device_map,
|
| 454 |
+
local_max_memory_per_gpu_gb=args.local_max_memory_per_gpu_gb,
|
| 455 |
+
local_processor_path=args.local_processor_path,
|
| 456 |
+
local_processor_class=args.local_processor_class,
|
| 457 |
+
force_api=args.force_api,
|
| 458 |
+
enable_stop=(not args.no_stop),
|
| 459 |
+
session_mode=args.session,
|
| 460 |
+
session_keep_turns=args.session_keep_turns,
|
| 461 |
+
)
|
| 462 |
+
)
|
| 463 |
+
args.model_name = model_name
|
| 464 |
+
return clients
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
def main() -> None:
|
| 468 |
+
parser = build_parser()
|
| 469 |
+
args = parser.parse_args()
|
| 470 |
+
|
| 471 |
+
logger.remove()
|
| 472 |
+
logger.add(sys.stderr, level="INFO")
|
| 473 |
+
os.makedirs(args.out_root, exist_ok=True)
|
| 474 |
+
|
| 475 |
+
clients = build_client_pool(args)
|
| 476 |
+
use_local_model = is_local_model_name(args.model_name) and (not args.force_api)
|
| 477 |
+
backend = "local_hf" if use_local_model else "api"
|
| 478 |
+
|
| 479 |
+
if args.use_json or (args.json_path and os.path.isfile(args.json_path)):
|
| 480 |
+
if not args.json_path or not args.image_root:
|
| 481 |
+
raise RuntimeError("JSON mode requires --json-path and --image-root")
|
| 482 |
+
logger.info(
|
| 483 |
+
f"Running Gemma hint generation in JSON mode... "
|
| 484 |
+
f"backend={backend} workers={args.workers} model={args.model_name}"
|
| 485 |
+
)
|
| 486 |
+
run_json_mode(args, clients)
|
| 487 |
+
return
|
| 488 |
+
|
| 489 |
+
if not args.data_dir:
|
| 490 |
+
raise RuntimeError("Parquet mode requires --data-dir")
|
| 491 |
+
logger.info(
|
| 492 |
+
f"Running Gemma hint generation in Parquet mode... "
|
| 493 |
+
f"backend={backend} workers={args.workers} model={args.model_name}"
|
| 494 |
+
)
|
| 495 |
+
run_parquet_mode(args, clients)
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
if __name__ == "__main__":
|
| 499 |
+
main()
|