Convert Lance weights to bf16 on download
Browse filesFiles changed (2)
7 unmodified lines89101112137 unmodified lines2122232425262789 unmodified lines117118119120121122123377 unmodified lines501502503504505506436 unmodified lines9439449459469479481 unmodified line9509519529539549555 unmodified lines96196296396496596613 unmodified lines9809819829839849859869879889899901262 unmodified lines225322542255225622572258582 unmodified lines28412842284328442845284628472848284928502851285228532854285528567 unmodified linesimport jsonimport osimport randomimport subprocessimport threadingimport time7 unmodified linesimport gradio as grimport torchfrom huggingface_hub import snapshot_downloadfrom safetensors.torch import load_filefrom transformers import set_seedfrom transformers.models.qwen2_5_vl.configuration_qwen2_5_vl import Qwen2_5_VLVisionConfig89 unmodified linesLANCE_PAPER_URL = "http://arxiv.org/abs/2605.18678"LANCE_HUGGING_FACE_URL = "https://huggingface.co/bytedance-research/Lance"LANCE_GITHUB_URL = "https://github.com/bytedance/Lance"LANCE_LOGO_PATH = REPO_ROOT / "assets" / "logo" / "lance-logo.webp"APP_CSS = """.gradio-container {377 unmodified linesborder-radius: 10px !important;}.generation-choice-grid .wrap label span {font-size: 16px !important;white-space: nowrap !important;436 unmodified lines]def ensure_model_assets(model_variant: Optional[str] = None) -> Path:model_base_dir = get_model_base_dir()os.environ["LANCE_MODEL_BASE_DIR"] = display_path(model_base_dir)1 unmodified linerequired_paths = get_required_model_asset_paths(model_base_dir, model_path)if all(path.exists() for path in required_paths):return model_pathdownloads_model_base_dir = Path("downloads")5 unmodified linesmodel_path = downloads_model_pathrequired_paths = downloads_required_pathsos.environ["LANCE_MODEL_BASE_DIR"] = display_path(model_base_dir)return model_pathauto_download = env_flag("LANCE_AUTO_DOWNLOAD", running_on_space())13 unmodified lineslocal_dir=str(model_base_dir),local_dir_use_symlinks=False,resume_download=True,))if snapshot_path != model_base_dir and not model_path.exists():os.environ["LANCE_MODEL_BASE_DIR"] = display_path(snapshot_path)model_path = get_model_path(model_variant)return model_path1262 unmodified linesdef get_pipeline_pool(task: str) -> PipelinePool:global ACTIVE_PIPELINE_POOLmodel_variant = get_task_model_variant(task)with ACTIVE_POOL_LOCK:if ACTIVE_PIPELINE_POOL is not None and ACTIVE_PIPELINE_POOL.model_variant == model_variant:582 unmodified linesif __name__ == "__main__":args = parse_args()os.environ["LANCE_GPUS"] = args.gpusresolved_model_path = ensure_model_assets(MODEL_VARIANT_VIDEO)print(f"[startup] Using Lance model path: {resolved_model_path}", flush=True)QUEUE_MAX_SIZE = args.queue_sizegpu_ids = parse_gpu_ids(args.gpus)ACTIVE_PIPELINE_POOL = PipelinePool(gpu_ids, model_variant=MODEL_VARIANT_VIDEO)ACTIVE_PIPELINE_POOL.initialize_all()demo = build_demo()demo.queue(max_size=args.queue_size,default_concurrency_limit=ACTIVE_PIPELINE_POOL.size,).launch(server_name=args.server_name,server_port=args.server_port,7 unmodified lines8910111213147 unmodified lines222324252627282989 unmodified lines119120121122123124125377 unmodified lines503504505506507508509510511512513514515436 unmodified lines952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251 unmodified line10271028102910301031103210335 unmodified lines103910401041104210431044104513 unmodified lines10591060106110621063106410651066106710681069107010711262 unmodified lines23342335233623372338233923402341234223432344582 unmodified lines29272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029517 unmodified linesimport jsonimport osimport randomimport shutilimport subprocessimport threadingimport time7 unmodified linesimport gradio as grimport torchfrom huggingface_hub import snapshot_downloadfrom safetensors import safe_openfrom safetensors.torch import load_file, save_filefrom transformers import set_seedfrom transformers.models.qwen2_5_vl.configuration_qwen2_5_vl import Qwen2_5_VLVisionConfig89 unmodified linesLANCE_PAPER_URL = "http://arxiv.org/abs/2605.18678"LANCE_HUGGING_FACE_URL = "https://huggingface.co/bytedance-research/Lance"LANCE_GITHUB_URL = "https://github.com/bytedance/Lance"LANCE_LOGO_PATH = REPO_ROOT / "assets" / "logo" / "lance-logo.png"APP_CSS = """.gradio-container {377 unmodified linesborder-radius: 10px !important;}.aspect-ratio-row .generation-choice-grid label,.video-duration-row .generation-choice-grid label {justify-content: flex-start !important;text-align: left !important;padding-left: 14px !important;}.generation-choice-grid .wrap label span {font-size: 16px !important;white-space: nowrap !important;436 unmodified lines]def get_model_download_allow_patterns(model_variant: Optional[str] = None) -> list[str]:variant = normalize_model_variant(model_variant)model_dir_name = MODEL_VARIANT_TO_DIR[variant]return [f"{model_dir_name}/**","Qwen2.5-VL-ViT/**","Wan2.2_VAE.pth","generation_config.json","llm_config.json","tokenizer.json","tokenizer_config.json","vocab.json","merges.txt","config.json",]def _get_safetensors_first_tensor_dtype(path: Path) -> Optional[torch.dtype]:if not path.exists():return Nonewith safe_open(str(path), framework="pt", device="cpu") as f:keys = list(f.keys())if not keys:return Nonereturn f.get_tensor(keys[0]).dtypedef convert_model_weights_to_bf16_inplace(model_path: Path) -> bool:weight_path = model_path / "model.safetensors"if not weight_path.exists():return Falsefirst_dtype = _get_safetensors_first_tensor_dtype(weight_path)if first_dtype is None or first_dtype == torch.bfloat16:return Falseif first_dtype != torch.float32:print(f"[startup] Skipping bf16 conversion for {weight_path} because the first tensor dtype is {first_dtype}.",flush=True,)return Falsetemp_path = weight_path.with_suffix(".bf16.safetensors.tmp")print(f"[startup] Converting {weight_path} to bf16 to reduce disk usage.", flush=True)with safe_open(str(weight_path), framework="pt", device="cpu") as f:metadata = f.metadata()tensor_names = list(f.keys())tensors = {}for name in tensor_names:tensor = f.get_tensor(name)tensors[name] = tensor.to(torch.bfloat16) if tensor.dtype == torch.float32 else tensorsave_file(tensors, str(temp_path), metadata=metadata)os.replace(temp_path, weight_path)print(f"[startup] Replaced original fp32 weights with bf16 weights at {weight_path}.", flush=True)return Truedef compact_downloaded_model_weights(model_base_dir: Path) -> None:for model_dir_name in (MODEL_VARIANT_TO_DIR[MODEL_VARIANT_IMAGE], MODEL_VARIANT_TO_DIR[MODEL_VARIANT_VIDEO]):model_path = model_base_dir / model_dir_nametry:convert_model_weights_to_bf16_inplace(model_path)except Exception as exc:print(f"[startup] bf16 compaction skipped for {display_path(model_path)}: {exc}", flush=True)def ensure_model_assets(model_variant: Optional[str] = None) -> Path:model_base_dir = get_model_base_dir()os.environ["LANCE_MODEL_BASE_DIR"] = display_path(model_base_dir)1 unmodified linerequired_paths = get_required_model_asset_paths(model_base_dir, model_path)if all(path.exists() for path in required_paths):compact_downloaded_model_weights(model_base_dir)return model_pathdownloads_model_base_dir = Path("downloads")5 unmodified linesmodel_path = downloads_model_pathrequired_paths = downloads_required_pathsos.environ["LANCE_MODEL_BASE_DIR"] = display_path(model_base_dir)compact_downloaded_model_weights(model_base_dir)return model_pathauto_download = env_flag("LANCE_AUTO_DOWNLOAD", running_on_space())13 unmodified lineslocal_dir=str(model_base_dir),local_dir_use_symlinks=False,resume_download=True,allow_patterns=get_model_download_allow_patterns(model_variant),))if snapshot_path != model_base_dir and not model_path.exists():os.environ["LANCE_MODEL_BASE_DIR"] = display_path(snapshot_path)model_path = get_model_path(model_variant)compact_downloaded_model_weights(model_base_dir)return model_path1262 unmodified linesdef get_pipeline_pool(task: str) -> PipelinePool:global ACTIVE_PIPELINE_POOLif not torch.cuda.is_available():raise RuntimeError("Lance inference requires a GPU. The Gradio UI can start on CPU, but generation is disabled ""until GPU hardware is attached.")model_variant = get_task_model_variant(task)with ACTIVE_POOL_LOCK:if ACTIVE_PIPELINE_POOL is not None and ACTIVE_PIPELINE_POOL.model_variant == model_variant:582 unmodified linesif __name__ == "__main__":args = parse_args()os.environ["LANCE_GPUS"] = args.gpusQUEUE_MAX_SIZE = args.queue_sizepreload_models = torch.cuda.is_available() and env_flag("LANCE_PRELOAD_MODELS", True)if preload_models:resolved_model_path = ensure_model_assets(MODEL_VARIANT_VIDEO)print(f"[startup] Using Lance model path: {resolved_model_path}", flush=True)gpu_ids = parse_gpu_ids(args.gpus)ACTIVE_PIPELINE_POOL = PipelinePool(gpu_ids, model_variant=MODEL_VARIANT_VIDEO)ACTIVE_PIPELINE_POOL.initialize_all()concurrency_limit = ACTIVE_PIPELINE_POOL.sizeelse:print("[startup] Skipping model preload. UI will launch without loading Lance weights until GPU hardware is available.",flush=True,)concurrency_limit = 1demo = build_demo()demo.queue(max_size=args.queue_size,default_concurrency_limit=concurrency_limit,).launch(server_name=args.server_name,server_port=args.server_port,
app.py+103-8
assets/logo/lance-logo.webp → assets/logo/lance-logo.pngRenamed

Large File Pointer Details
- SHA256: 5359f986a6a29e25b4eb92fd470e74c83d92581dc6fb22d2c4ac789637842934
- Pointer size: 131 Bytes
- Size of remote file: 461 kB

Large File Pointer Details
- SHA256: 14ea43b8d4cdb9458b76771b6cda11d843cbda7a402bee5088b6e80d52a4b80c
- Pointer size: 131 Bytes
- Size of remote file: 724 kB