Spaces:
Running
Running
optimize 2 claude
Browse files14 unmodified lines151617181920212223173 unmodified lines197198199200201202203204205206207208209210211212213214215216217218219220353 unmodified lines57457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062114 unmodified lines)# ---------------------------------------------------------------------------# Step 4: Pin CPU thread count to the box's vCPU count. Left unpinned,# PyTorch's default intra-op threading can oversubscribe a 2-vCPU host and# cause contention between concurrent encode() calls.# ---------------------------------------------------------------------------torch.set_num_threads(2)173 unmodified linesThis means a request with N jobs makes a fixed ~4 model.encode() callstotal instead of up to 4*N + 1, regardless of N. Scoring math andoutput are unchanged — this is purely a batching optimization."""def __init__(self,semantic_model_name: str = "jinaai/jina-embeddings-v2-base-en",title_model_name: str = "TechWolf/JobBERT-v2",skill_aliases: Optional[Dict[str, List[str]]] = None,category_skills: Optional[Dict[str, Set[str]]] = None,) -> None:self._model = SentenceTransformer(semantic_model_name, trust_remote_code=True)try:self._title_model = SentenceTransformer("TechWolf/JobBERT-v3")except Exception:self._title_model = SentenceTransformer(title_model_name)self._aliases: Dict[str, List[str]] = skill_aliases or DEFAULT_SKILL_ALIASESself._category_skills: Dict[str, Set[str]] = category_skills or DEFAULT_CATEGORY_SKILLS# ------------------------------------------------------------------# Public: single-job prediction (backward-compatible)# ------------------------------------------------------------------353 unmodified lines)return text[:4000]@staticmethoddef _chunk_words(text: str) -> List[str]:"""Split long text into overlapping ~180-word chunks (unchanged logic)."""words = text.split()if len(words) <= 180:return [text]step = 135return [" ".join(words[i: i + 180]) for i in range(0, len(words), step)]def _embed_batch_texts(self, texts: List[str]) -> np.ndarray:"""Embed a list of texts in a SINGLE batched encode() call.Each text is chunked internally (same word-chunking-and-mean-poolingbehavior as the original per-item _embed()), but all chunks acrossALL input texts are flattened into one encode() call, then averagedback per input text. This is the core batching win for step 2."""if not texts:return np.zeros((0, 384), dtype="float32")all_parts: List[str] = []boundaries: List[Tuple[int, int]] = []for t in texts:parts = self._chunk_words(t) if t else [""]start = len(all_parts)all_parts.extend(parts)boundaries.append((start, len(all_parts)))vectors = self._model.encode(all_parts, normalize_embeddings=True, show_progress_bar=False, batch_size=32)vectors = np.asarray(vectors)dim = vectors.shape[1] if vectors.ndim == 2 else 384result = np.zeros((len(texts), dim), dtype="float32")for i, (s, e) in enumerate(boundaries):result[i] = np.mean(vectors[s:e], axis=0)return resultdef _embed(self, text: str) -> np.ndarray:"""Encode a single text → normalised float32 vector (chunked internally)."""return self._embed_batch_texts([text])[0]def _embed_title_batch(self, titles: List[str]) -> np.ndarray:14 unmodified lines151617181920212223242526272829303132333435173 unmodified lines209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319353 unmodified lines67367467567667767867968068168268368468568668768868969069169269369469569669769869914 unmodified lines)# ---------------------------------------------------------------------------# Requires (for the ONNX path): pip install "optimum[onnxruntime]" onnxruntime# If these aren't installed, model loading below automatically falls back to# the plain PyTorch backend -- nothing crashes, it just runs at pre-ONNX speed.# ---------------------------------------------------------------------------try:import onnxruntime as ort_ONNXRUNTIME_AVAILABLE = Trueexcept ImportError:_ONNXRUNTIME_AVAILABLE = False# ---------------------------------------------------------------------------# Pin CPU thread count to the box's vCPU count. Left unpinned, PyTorch's# (and separately, ONNX Runtime's) default intra-op threading can# oversubscribe a 2-vCPU host and cause contention between concurrent# encode() calls.# ---------------------------------------------------------------------------torch.set_num_threads(2)173 unmodified linesThis means a request with N jobs makes a fixed ~4 model.encode() callstotal instead of up to 4*N + 1, regardless of N. Scoring math andoutput are unchanged — this is purely a batching optimization.Text is no longer manually chunked into overlapping ~180-word windowsbefore embedding. jina-embeddings-v2-base-en natively supports up to8192 tokens (ALiBi long-context), so the 4000-char-truncated job/CVtext fits in a single forward pass. The chunk-and-mean-pool logic wasleft over from a shorter-context model and was silently tripling thenumber of forward passes per job for descriptions over ~180 words.Both models are loaded via the ONNX Runtime backend (with int8quantization where a quantized export is available on the model repo)for faster CPU inference, with automatic fallback to plain PyTorch ifONNX packages or ONNX weights aren't available — see _load_model()."""# Candidate ONNX file names to try, in preference order (most# aggressively quantized first). `None` means "let sentence-transformers# auto-select / auto-export the default ONNX model". Not every model# repo ships every variant, so we try each and move on if one 404s._ONNX_FILE_CANDIDATES: List[Optional[str]] = ["onnx/model_qint8_avx512_vnni.onnx","onnx/model_quantized.onnx","onnx/model_qint8.onnx","onnx/model_int8.onnx","onnx/model.onnx",None,]def __init__(self,semantic_model_name: str = "jinaai/jina-embeddings-v2-base-en",title_model_name: str = "TechWolf/JobBERT-v2",skill_aliases: Optional[Dict[str, List[str]]] = None,category_skills: Optional[Dict[str, Set[str]]] = None,use_onnx: bool = True,) -> None:self._model = self._load_model(semantic_model_name, use_onnx=use_onnx, trust_remote_code=True)try:self._title_model = self._load_model("TechWolf/JobBERT-v3", use_onnx=use_onnx, trust_remote_code=False)except Exception:self._title_model = self._load_model(title_model_name, use_onnx=use_onnx, trust_remote_code=False)self._aliases: Dict[str, List[str]] = skill_aliases or DEFAULT_SKILL_ALIASESself._category_skills: Dict[str, Set[str]] = category_skills or DEFAULT_CATEGORY_SKILLS# ------------------------------------------------------------------# Internal: load a SentenceTransformer via ONNX Runtime if possible,# trying quantized variants first, falling back to plain PyTorch.# ------------------------------------------------------------------@classmethoddef _load_model(cls,model_name: str,use_onnx: bool = True,trust_remote_code: bool = False,) -> SentenceTransformer:if use_onnx and _ONNXRUNTIME_AVAILABLE:session_options = Nonetry:session_options = ort.SessionOptions()session_options.intra_op_num_threads = 2session_options.inter_op_num_threads = 1except Exception:session_options = Nonefor file_name in cls._ONNX_FILE_CANDIDATES:try:model_kwargs: Dict[str, Any] = {}if file_name:model_kwargs["file_name"] = file_nameif session_options is not None:model_kwargs["session_options"] = session_optionsmodel = SentenceTransformer(model_name,backend="onnx",trust_remote_code=trust_remote_code,model_kwargs=model_kwargs,)print(f"[JobMatcher] Loaded '{model_name}' via ONNX Runtime "f"(file={file_name or 'auto-export'}).")return modelexcept Exception as exc:print(f"[JobMatcher] ONNX load attempt failed for "f"'{model_name}' (file={file_name or 'auto-export'}): {exc}")elif use_onnx and not _ONNXRUNTIME_AVAILABLE:print("[JobMatcher] onnxruntime/optimum not installed — "f"falling back to PyTorch backend for '{model_name}'. "'Install with: pip install "optimum[onnxruntime]" onnxruntime')print(f"[JobMatcher] Loading '{model_name}' via PyTorch backend.")return SentenceTransformer(model_name, trust_remote_code=trust_remote_code)# ------------------------------------------------------------------# Public: single-job prediction (backward-compatible)# ------------------------------------------------------------------353 unmodified lines)return text[:4000]def _embed_batch_texts(self, texts: List[str]) -> np.ndarray:"""Embed a list of texts in a SINGLE batched encode() call.No manual word-chunking: jina-embeddings-v2-base-en nativelysupports sequences up to 8192 tokens (ALiBi long-context), and jobtext is already truncated to 4000 chars upstream, so it fits inone forward pass per item. This removes what used to be up to 3xredundant forward passes per job for descriptions over ~180 words."""if not texts:return np.zeros((0, 384), dtype="float32")safe_texts = [t if t else "" for t in texts]vectors = self._model.encode(safe_texts, normalize_embeddings=True, show_progress_bar=False, batch_size=32)return np.asarray(vectors, dtype="float32")def _embed(self, text: str) -> np.ndarray:"""Encode a single text → normalised float32 vector (single forward pass)."""return self._embed_batch_texts([text])[0]def _embed_title_batch(self, titles: List[str]) -> np.ndarray:
services/job_matcher.py+114-36