Download classifier.py from RohanTheZ/enzyme-viva: direct link, hf CLI and curl.
- Browser
- Download file 2.27 kB
-
https://huggingface.co/RohanTheZ/enzyme-viva/resolve/main/classifier.py
- Command line
-
hf download hf://RohanTheZ/enzyme-viva/classifier.py
-
curl -L -o classifier.py https://huggingface.co/RohanTheZ/enzyme-viva/resolve/main/classifier.py
2.27 kB
| """Step 4: the fine-tuned ESM2-8M classifier, run on weak queries. | |
| For queries whose best hit is below 40% identity, the hits are only distant relatives and often | |
| point to the wrong EC. The classifier reads the sequence itself and gives a probability for each | |
| of the 4,614 training ECs. Its top 10 ECs and probabilities are passed to the reranker as extra | |
| features (see rerank.add_classifier_features). | |
| The model runs in NumPy (esm_numpy.py) because the evaluator has no GPU and no PyTorch. It is slow | |
| on CPU, so it runs on two processes, weakest queries first, and stops at CLASSIFIER_UNTIL_SECONDS. | |
| """ | |
| import time | |
| from multiprocessing import Pool | |
| from pathlib import Path | |
| import config | |
| from esm_numpy import ECClassifierNumpy | |
| WEIGHTS = Path(__file__).parent / 'weights' | |
| # Loaded in the main process before the two worker processes start. The workers are copies of the | |
| # main process (fork), so they already have the model in memory and do not load it again. | |
| model = None | |
| def predict_one(sequence): | |
| return model.predict(sequence) | |
| def run_classifier(query_ids, sequence_of, start): | |
| """Top 10 ECs and probabilities for each query, in the given order, until the time limit. | |
| Returns {query id: (ECs, probabilities)}. | |
| This step is optional: if anything goes wrong (an error, a crashed or stuck worker), it stops | |
| and returns what it has. Queries without classifier output still get a prediction from the reranker. | |
| """ | |
| global model | |
| results = {} | |
| if not query_ids: | |
| return results | |
| pool = None | |
| try: | |
| model = ECClassifierNumpy(str(WEIGHTS / 'ec_classifier.npz'), str(WEIGHTS / 'ec_classes.json')) | |
| pool = Pool(2) | |
| answers = pool.imap(predict_one, [sequence_of[q] for q in query_ids]) | |
| for q in query_ids: | |
| time_left = config.CLASSIFIER_UNTIL_SECONDS - (time.time() - start) | |
| if time_left <= 0: | |
| break | |
| # Wait at most until the time limit for the next answer; a stuck worker raises TimeoutError | |
| results[q] = answers.next(timeout=time_left) | |
| except Exception as error: | |
| print('classifier stage stopped early:', repr(error), flush=True) | |
| finally: | |
| if pool is not None: | |
| pool.terminate() | |
| return results | |