rocco commited on
Commit ·
d4e77c6
1
Parent(s): 08a464b
Support CPU GPU and ZeroGPU
Browse filesFiles changed (2)
- app.py+47-20
- requirements.txt+1
5 unmodified lines678910114 unmodified lines16171819202120 unmodified lines4243444546474849505152535455565758596061626364656667686970717273745 unmodified linesimport refrom pathlib import Pathimport gradio as grfrom sentence_transformers import SentenceTransformer, util4 unmodified lineslogging.basicConfig(level=logging.INFO)def load_descriptions(tsv_path, pickle_path):# Only load the maintainer's trusted pickle; never accept user-uploaded pickles.with open(pickle_path, 'rb') as f:20 unmodified linesreturn labels, [descriptions[label] for label in labels]def create_demo():if not MODEL_ID:raise ValueError('Set MODEL_ID in Space Settings → Variables to your trained model repository ID.')labels, descriptions = load_descriptions(ROOT / 'data/WorldsLangs.tsv', ROOT / 'data/all_stats.pkl')# Load the trained LIBE checkpoint, not the unmodified base LaBSE model.model = SentenceTransformer(MODEL_ID, device='cpu', revision=MODEL_REVISION,token=os.environ.get('HF_TOKEN') or None,)corpus_embeddings = model.encode(descriptions, convert_to_tensor=True, normalize_embeddings=True,batch_size=16, show_progress_bar=True,).to('cpu')top_k = min(5, len(labels))def identify(text):text = (text or '').strip()if not text:raise gr.Error('Please enter some text.')if len(text) > MAX_CHARS:raise gr.Error(f'Please use at most {MAX_CHARS:,} characters.')query_embeddings = model.encode([text], convert_to_tensor=True, normalize_embeddings=True,show_progress_bar=False,).to('cpu')hits = util.semantic_search(query_embeddings, corpus_embeddings, top_k=top_k)[0]best = hits[0]i = best['corpus_id']5 unmodified lines6789101112134 unmodified lines181920212223242526272829303132333435363738394041424344454620 unmodified lines6768697071727374757677787980818283848586878889909192939495969798991001015 unmodified linesimport refrom pathlib import Pathimport spaces # Import before torch / sentence_transformers for ZeroGPU.import torchimport gradio as grfrom sentence_transformers import SentenceTransformer, util4 unmodified lineslogging.basicConfig(level=logging.INFO)def select_device(zero_gpu_flag, cuda_available):is_zero = zero_gpu_flag.strip().lower() in {'1', 'true', 'yes', 'on', 't'}return is_zero, 'cuda' if is_zero or cuda_available else 'cpu'IS_ZERO_GPU, DEVICE = select_device(os.environ.get('SPACES_ZERO_GPU', ''), torch.cuda.is_available())logging.info('LIBE hardware: %s', 'ZeroGPU' if IS_ZERO_GPU else DEVICE)@spaces.GPU(duration=30)def encode_query(text):# CUDA computation occurs inside the allocation on ZeroGPU.# The decorator is a passthrough on ordinary CPU/GPU hardware.with torch.inference_mode():return model.encode([text], convert_to_tensor=True, normalize_embeddings=True,show_progress_bar=False, device=DEVICE,).cpu()def load_descriptions(tsv_path, pickle_path):# Only load the maintainer's trusted pickle; never accept user-uploaded pickles.with open(pickle_path, 'rb') as f:20 unmodified linesreturn labels, [descriptions[label] for label in labels]if not MODEL_ID:raise ValueError('Set MODEL_ID in Space Settings → Variables to your trained model repository ID.')labels, descriptions = load_descriptions(ROOT / 'data/WorldsLangs.tsv', ROOT / 'data/all_stats.pkl')# Load the trained LIBE checkpoint, not the unmodified base LaBSE model.model = SentenceTransformer(MODEL_ID, device='cpu' if IS_ZERO_GPU else DEVICE, revision=MODEL_REVISION,token=os.environ.get('HF_TOKEN') or None,)corpus_embeddings = model.encode(descriptions, convert_to_tensor=True, normalize_embeddings=True,batch_size=16, show_progress_bar=True,).to('cpu')top_k = min(5, len(labels))# Place model on CUDA outside the decorated function; ZeroGPU emulates this# allocation until a request receives a real GPU. No GPU inference at startup.model.to(DEVICE)def create_demo():def identify(text):text = (text or '').strip()if not text:raise gr.Error('Please enter some text.')if len(text) > MAX_CHARS:raise gr.Error(f'Please use at most {MAX_CHARS:,} characters.')query_embeddings = encode_query(text)hits = util.semantic_search(query_embeddings, corpus_embeddings, top_k=top_k)[0]best = hits[0]i = best['corpus_id']
1sentence-transformers>=3.4,<612sentence-transformers>=3.4,<6spaces
app.py+47-20
requirements.txt+1