Spaces:
Running
Running
ThorbenFroehlking commited on
Commit ·
78b2c3a
1
Parent(s): af13564
Update
Browse filesFiles changed (2)
- app.py+197-112
- model_loader.py+26-19
18 unmodified lines1920212223242 unmodified lines272829303132333435363738391 unmodified line41424344454647484950515253545556575859606114 unmodified lines76777879808182838485868788899091929394959697983 unmodified lines10210310410510610710823 unmodified lines13213313413513613719 unmodified lines15715815916016116216320 unmodified lines18418518618718818919019119218 unmodified lines21121221321421521621721821922022122222339 unmodified lines263264265266267268269270271272273274275135 unmodified lines41141241341441541670 unmodified lines4874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835841 unmodified line58658758858959059159259334 unmodified lines6286296306316326336346356366376386396406416426436445 unmodified lines65065165265318 unmodified linesimport reimport pandas as pdimport copyimport transformersfrom transformers import AutoTokenizer, DataCollatorForTokenClassification2 unmodified linesfrom scipy.special import expit# Load model and move to device#checkpoint = 'ThorbenF/prot_t5_xl_uniref50'#checkpoint = 'ThorbenF/prot_t5_xl_uniref50_cryptic'#checkpoint = 'ThorbenF/prot_t5_xl_uniref50_database'#checkpoint = 'ThorbenF/prot_t5_xl_uniref50_full'#checkpoint = 'ThorbenF/prot_t5_xl_uniref50_0925'#checkpoint = 'ThorbenF/prot_t5_xl_uniref50_0925_v2'checkpoint = 'ThorbenF/prot_t5_xl_uniref50_full_v2'max_length = 1500model, tokenizer = load_model(checkpoint, max_length)1 unmodified linemodel.to(device)model.eval()def normalize_scores(scores):min_score = np.min(scores)max_score = np.max(scores)return (scores - min_score) / (max_score - min_score) if max_score > min_score else scoresdef read_mol(pdb_path):"""Read PDB file and return its content as a string"""with open(pdb_path, 'r') as f:return f.read()def fetch_structure(pdb_id: str, output_dir: str = ".") -> str:"""Fetch the structure file for a given PDB ID. Prioritizes CIF files.If a structure file already exists locally, it uses that."""file_path = download_structure(pdb_id, output_dir)return file_path14 unmodified linesreturn file_pathreturn Nonedef convert_cif_to_pdb(cif_path: str, output_dir: str = ".") -> str:"""Convert a CIF file to PDB format using BioPython and return the PDB file path."""pdb_path = os.path.join(output_dir, os.path.basename(cif_path).replace('.cif', '.pdb'))parser = MMCIFParser(QUIET=True)structure = parser.get_structure('protein', cif_path)io = PDBIO()io.set_structure(structure)io.save(pdb_path)return pdb_pathdef fetch_pdb(pdb_id):pdb_path = fetch_structure(pdb_id)_, ext = os.path.splitext(pdb_path)if ext == '.cif':pdb_path = convert_cif_to_pdb(pdb_path)return pdb_pathdef create_chain_specific_pdb(input_pdb: str, chain_id: str, residue_scores: list, protein_residues: list) -> str:3 unmodified linesparser = PDBParser(QUIET=True)structure = parser.get_structure('protein', input_pdb)output_pdb = f"{os.path.splitext(input_pdb)[0]}_{chain_id}_predictions_scores.pdb"# Create scores dictionary for easy lookupscores_dict = {resi: score for resi, score in residue_scores}23 unmodified linesio.set_structure(structure[0])io.save(output_pdb, selector)return output_pdbdef generate_pymol_commands(pdb_id, segment, residues_by_bracket, current_time, score_type):19 unmodified lines# Add PyMOL commands for each score bracketfor bracket, residues in residues_by_bracket.items():if residues: # Only add commands if there are residues in this bracketcolor = bracket_colors[bracket]resi_list = '+'.join(map(str, residues))pymol_commands += f"""20 unmodified linesreturn result_strdef process_pdb(pdb_id_or_file, segment, score_type='normalized'):# Determine if input is a PDB ID or file pathif pdb_id_or_file.endswith('.pdb'):18 unmodified linessequence_id = [res.id[1] for res in protein_residues]input_ids = tokenizer(" ".join(sequence), return_tensors="pt").input_ids.to(device)with torch.no_grad():outputs = model(input_ids).logits.detach().cpu().numpy().squeeze()# Calculate scores and normalize themraw_scores = expit(outputs[:, 1] - outputs[:, 0])normalized_scores = normalize_scores(raw_scores)# Choose which scores to use based on score_typedisplay_scores = normalized_scores if score_type == 'normalized' else raw_scores39 unmodified linesmol_vis = molecule(pdb_path, residue_scores, segment)# Create prediction fileprediction_file = f"{pdb_id}_{display_score_type.lower()}_binding_site_residues.txt"with open(prediction_file, "w") as f:f.write(result_str)scored_pdb_name = f"{pdb_id}_{segment}_{display_score_type.lower()}_predictions_scores.pdb"os.rename(scored_pdb, scored_pdb_name)return pymol_commands, mol_vis, [prediction_file, scored_pdb_name], raw_residue_scores, norm_residue_scores, pdb_id, segmentdef molecule(input_pdb, residue_scores=None, segment='A'):135 unmodified lines</html>"""# Return the HTML content within an iframe safely encoded for special charactersreturn f'<iframe width="100%" height="700" srcdoc="{html_content.replace(chr(34), """).replace(chr(39), "'")}"></iframe>'70 unmodified lineslast_pdb_id = gr.State(None)def process_interface(mode, pdb_id, pdb_file, chain_id, score_type_val):selected_score_type = 'normalized' if score_type_val == "Normalized Scores" else 'raw'# First get the actual PDB file pathif mode == "PDB ID":pdb_path = fetch_pdb(pdb_id) # Get the actual file pathpymol_cmd, mol_vis, files, raw_scores, norm_scores, pdb_id_result, segment = process_pdb(pdb_path, chain_id, selected_score_type)# Store the actual file path, not just the PDB IDreturn pymol_cmd, mol_vis, files, raw_scores, norm_scores, pdb_path, chain_id, pdb_id_resultelif mode == "Upload File":_, ext = os.path.splitext(pdb_file.name)file_path = os.path.join('./', f"{_}{ext}")if ext == '.cif':pdb_path = convert_cif_to_pdb(file_path)else:pdb_path = file_pathpymol_cmd, mol_vis, files, raw_scores, norm_scores, pdb_id_result, segment = process_pdb(pdb_path, chain_id, selected_score_type)return pymol_cmd, mol_vis, files, raw_scores, norm_scores, pdb_path, chain_id, pdb_id_resultdef update_visualization_and_files(score_type_val, raw_scores, norm_scores, pdb_path, segment, pdb_id):if raw_scores is None or norm_scores is None or pdb_path is None or segment is None or pdb_id is None:return None, None, None# Choose scores based on radio button selectionselected_score_type = 'normalized' if score_type_val == "Normalized Scores" else 'raw'selected_scores = norm_scores if selected_score_type == 'normalized' else raw_scores# Generate visualization with selected scoresmol_vis = molecule(pdb_path, selected_scores, segment)# Generate PyMOL commands and downloadable files# Get structure for residue info_, ext = os.path.splitext(pdb_path)parser = MMCIFParser(QUIET=True) if ext == '.cif' else PDBParser(QUIET=True)structure = parser.get_structure('protein', pdb_path)chain = structure[0][segment]protein_residues = [res for res in chain if is_aa(res)]sequence = "".join(seq1(res.resname) for res in protein_residues)# Define score bracketsscore_brackets = {"0.0-0.2": (0.0, 0.2),"0.2-0.4": (0.2, 0.4),"0.4-0.6": (0.4, 0.6),"0.6-0.8": (0.6, 0.8),"0.8-1.0": (0.8, 1.0)}# Initialize a dictionary to store residues by bracketresidues_by_bracket = {bracket: [] for bracket in score_brackets}# Categorize residues into bracketsfor resi, score in selected_scores:for bracket, (lower, upper) in score_brackets.items():if lower <= score < upper:residues_by_bracket[bracket].append(resi)break# Generate timestampcurrent_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")# Generate result text and PyMOL commands based on score typedisplay_score_type = "Normalized" if selected_score_type == 'normalized' else "Raw"scores_array = [score for _, score in selected_scores]result_str = generate_results_text(pdb_id, segment, residues_by_bracket, protein_residues, sequence,scores_array, current_time, display_score_type)pymol_commands = generate_pymol_commands(pdb_id, segment, residues_by_bracket, current_time, display_score_type)# Create chain-specific PDB with scores in B-factorscored_pdb = create_chain_specific_pdb(pdb_path, segment, selected_scores, protein_residues)# Create prediction fileprediction_file = f"{pdb_id}_{display_score_type.lower()}_binding_site_residues.txt"with open(prediction_file, "w") as f:f.write(result_str)scored_pdb_name = f"{pdb_id}_{segment}_{display_score_type.lower()}_predictions_scores.pdb"os.rename(scored_pdb, scored_pdb_name)return mol_vis, pymol_commands, [prediction_file, scored_pdb_name]def fetch_interface(mode, pdb_id, pdb_file):if mode == "PDB ID":return fetch_pdb(pdb_id)elif mode == "Upload File":_, ext = os.path.splitext(pdb_file.name)file_path = os.path.join('./', f"{_}{ext}")if ext == '.cif':pdb_path = convert_cif_to_pdb(file_path)else:pdb_path= file_pathreturn pdb_pathdef toggle_mode(selected_mode):1 unmodified linereturn gr.update(visible=True), gr.update(visible=False)else:return gr.update(visible=False), gr.update(visible=True)mode.change(toggle_mode,34 unmodified lines)def predict_utils(sequence):input_ids = tokenizer(" ".join(sequence), return_tensors="pt").input_ids.to(device)with torch.no_grad():outputs = model(input_ids).logits.detach().cpu().numpy().squeeze()raw_scores = expit(outputs[:, 1] - outputs[:, 0])normalized_scores = normalize_scores(raw_scores)return {"raw_scores": raw_scores.tolist(),"normalized_scores": normalized_scores.tolist()}dummy_input = gr.Textbox(visible=False)dummy_output = gr.Textbox(visible=False)5 unmodified linesoutputs=[dummy_output])demo.launch(share=True)18 unmodified lines19202122232425262728292 unmodified lines32333435363738394041424344454647484950515253545556571 unmodified line59606162636465666768697071727374757677787980818283848586878889909114 unmodified lines1061071081091101111121131141151161171181191201211221231241251261271281291301311321331343 unmodified lines13813914014114214314423 unmodified lines16816917017117217317417517619 unmodified lines19619719819920020120220 unmodified lines22322422522622722818 unmodified lines24724824925025125225325425525625725825926026126226326426526626726826939 unmodified lines309310311312313314315316317318319320321322323324325135 unmodified lines46146246346446546646746846970 unmodified lines5405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526531 unmodified line65565665765865966034 unmodified lines6956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287295 unmodified lines73573673773818 unmodified linesimport reimport pandas as pdimport copyimport gcimport tempfileimport shutilimport atexitimport weakrefimport transformersfrom transformers import AutoTokenizer, DataCollatorForTokenClassification2 unmodified linesfrom scipy.special import expit# Create a temporary directory for this sessionTEMP_DIR = tempfile.mkdtemp(prefix="protein_binding_")print(f"Using temporary directory: {TEMP_DIR}")# Registry to track created files for cleanup_file_registry = weakref.WeakSet()def cleanup_temp_files():"""Clean up temporary directory on exit"""try:if os.path.exists(TEMP_DIR):shutil.rmtree(TEMP_DIR)print(f"Cleaned up temporary directory: {TEMP_DIR}")except Exception as e:print(f"Error cleaning up temp directory: {e}")# Register cleanup functionatexit.register(cleanup_temp_files)# Load model and move to devicecheckpoint = 'ThorbenF/prot_t5_xl_uniref50_full_v2'max_length = 1500model, tokenizer = load_model(checkpoint, max_length)1 unmodified linemodel.to(device)model.eval()def cleanup_files(*file_paths):"""Helper function to clean up files"""for path in file_paths:if path and os.path.exists(path):try:os.remove(path)except Exception as e:print(f"Could not remove {path}: {e}")def normalize_scores(scores):min_score = np.min(scores)max_score = np.max(scores)normalized = (scores - min_score) / (max_score - min_score) if max_score > min_score else scoresreturn normalizeddef read_mol(pdb_path):"""Read PDB file and return its content as a string"""with open(pdb_path, 'r') as f:return f.read()def fetch_structure(pdb_id: str, output_dir: str = None) -> str:"""Fetch the structure file for a given PDB ID. Prioritizes CIF files.If a structure file already exists locally, it uses that."""if output_dir is None:output_dir = TEMP_DIRfile_path = download_structure(pdb_id, output_dir)return file_path14 unmodified linesreturn file_pathreturn Nonedef convert_cif_to_pdb(cif_path: str, output_dir: str = None) -> str:"""Convert a CIF file to PDB format using BioPython and return the PDB file path."""if output_dir is None:output_dir = TEMP_DIRpdb_path = os.path.join(output_dir, os.path.basename(cif_path).replace('.cif', '.pdb'))parser = MMCIFParser(QUIET=True)structure = parser.get_structure('protein', cif_path)io = PDBIO()io.set_structure(structure)io.save(pdb_path)# Clean up CIF file after conversioncleanup_files(cif_path)return pdb_pathdef fetch_pdb(pdb_id):pdb_path = fetch_structure(pdb_id, TEMP_DIR)_, ext = os.path.splitext(pdb_path)if ext == '.cif':pdb_path = convert_cif_to_pdb(pdb_path, TEMP_DIR)return pdb_pathdef create_chain_specific_pdb(input_pdb: str, chain_id: str, residue_scores: list, protein_residues: list) -> str:3 unmodified linesparser = PDBParser(QUIET=True)structure = parser.get_structure('protein', input_pdb)output_pdb = os.path.join(TEMP_DIR, f"{os.path.splitext(os.path.basename(input_pdb))[0]}_{chain_id}_predictions_scores.pdb")# Create scores dictionary for easy lookupscores_dict = {resi: score for resi, score in residue_scores}23 unmodified linesio.set_structure(structure[0])io.save(output_pdb, selector)# Clear referencesdel structure, io, selector, scores_dictreturn output_pdbdef generate_pymol_commands(pdb_id, segment, residues_by_bracket, current_time, score_type):19 unmodified lines# Add PyMOL commands for each score bracketfor bracket, residues in residues_by_bracket.items():if residues:color = bracket_colors[bracket]resi_list = '+'.join(map(str, residues))pymol_commands += f"""20 unmodified linesreturn result_strdef process_pdb(pdb_id_or_file, segment, score_type='normalized'):# Determine if input is a PDB ID or file pathif pdb_id_or_file.endswith('.pdb'):18 unmodified linessequence_id = [res.id[1] for res in protein_residues]input_ids = tokenizer(" ".join(sequence), return_tensors="pt").input_ids.to(device)with torch.no_grad():outputs = model(input_ids).logitsoutputs_cpu = outputs.detach().cpu().numpy().squeeze()# Explicitly delete GPU tensorsdel outputs, input_idsif torch.cuda.is_available():torch.cuda.empty_cache()# Calculate scores and normalize themraw_scores = expit(outputs_cpu[:, 1] - outputs_cpu[:, 0])normalized_scores = normalize_scores(raw_scores)# Clear outputs_cpudel outputs_cpu# Choose which scores to use based on score_typedisplay_scores = normalized_scores if score_type == 'normalized' else raw_scores39 unmodified linesmol_vis = molecule(pdb_path, residue_scores, segment)# Create prediction fileprediction_file = os.path.join(TEMP_DIR, f"{pdb_id}_{display_score_type.lower()}_binding_site_residues.txt")with open(prediction_file, "w") as f:f.write(result_str)scored_pdb_name = os.path.join(TEMP_DIR, f"{pdb_id}_{segment}_{display_score_type.lower()}_predictions_scores.pdb")os.rename(scored_pdb, scored_pdb_name)# Clear large objects from memorydel structure, chain, protein_residues, raw_scores, normalized_scores, display_scoresgc.collect()return pymol_commands, mol_vis, [prediction_file, scored_pdb_name], raw_residue_scores, norm_residue_scores, pdb_id, segmentdef molecule(input_pdb, residue_scores=None, segment='A'):135 unmodified lines</html>"""# Clear mol from memory after usedel mol# Return the HTML content within an iframe safely encoded for special charactersreturn f'<iframe width="100%" height="700" srcdoc="{html_content.replace(chr(34), """).replace(chr(39), "'")}"></iframe>'70 unmodified lineslast_pdb_id = gr.State(None)def process_interface(mode, pdb_id, pdb_file, chain_id, score_type_val):try:selected_score_type = 'normalized' if score_type_val == "Normalized Scores" else 'raw'# First get the actual PDB file pathif mode == "PDB ID":pdb_path = fetch_pdb(pdb_id)pymol_cmd, mol_vis, files, raw_scores, norm_scores, pdb_id_result, segment = process_pdb(pdb_path, chain_id, selected_score_type)return pymol_cmd, mol_vis, files, raw_scores, norm_scores, pdb_path, chain_id, pdb_id_resultelif mode == "Upload File":_, ext = os.path.splitext(pdb_file.name)file_path = os.path.join(TEMP_DIR, f"{os.path.basename(pdb_file.name)}")# Copy uploaded file to temp directoryshutil.copy(pdb_file.name, file_path)if ext == '.cif':pdb_path = convert_cif_to_pdb(file_path, TEMP_DIR)else:pdb_path = file_pathpymol_cmd, mol_vis, files, raw_scores, norm_scores, pdb_id_result, segment = process_pdb(pdb_path, chain_id, selected_score_type)return pymol_cmd, mol_vis, files, raw_scores, norm_scores, pdb_path, chain_id, pdb_id_resultfinally:# Force garbage collection after processinggc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()def update_visualization_and_files(score_type_val, raw_scores, norm_scores, pdb_path, segment, pdb_id):if raw_scores is None or norm_scores is None or pdb_path is None or segment is None or pdb_id is None:return None, None, Nonetry:# Choose scores based on radio button selectionselected_score_type = 'normalized' if score_type_val == "Normalized Scores" else 'raw'selected_scores = norm_scores if selected_score_type == 'normalized' else raw_scores# Generate visualization with selected scoresmol_vis = molecule(pdb_path, selected_scores, segment)# Generate PyMOL commands and downloadable files# Get structure for residue info_, ext = os.path.splitext(pdb_path)parser = MMCIFParser(QUIET=True) if ext == '.cif' else PDBParser(QUIET=True)structure = parser.get_structure('protein', pdb_path)chain = structure[0][segment]protein_residues = [res for res in chain if is_aa(res)]sequence = "".join(seq1(res.resname) for res in protein_residues)# Define score bracketsscore_brackets = {"0.0-0.2": (0.0, 0.2),"0.2-0.4": (0.2, 0.4),"0.4-0.6": (0.4, 0.6),"0.6-0.8": (0.6, 0.8),"0.8-1.0": (0.8, 1.0)}# Initialize a dictionary to store residues by bracketresidues_by_bracket = {bracket: [] for bracket in score_brackets}# Categorize residues into bracketsfor resi, score in selected_scores:for bracket, (lower, upper) in score_brackets.items():if lower <= score < upper:residues_by_bracket[bracket].append(resi)break# Generate timestampcurrent_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")# Generate result text and PyMOL commands based on score typedisplay_score_type = "Normalized" if selected_score_type == 'normalized' else "Raw"scores_array = [score for _, score in selected_scores]result_str = generate_results_text(pdb_id, segment, residues_by_bracket, protein_residues, sequence,scores_array, current_time, display_score_type)pymol_commands = generate_pymol_commands(pdb_id, segment, residues_by_bracket, current_time, display_score_type)# Create chain-specific PDB with scores in B-factorscored_pdb = create_chain_specific_pdb(pdb_path, segment, selected_scores, protein_residues)# Create prediction fileprediction_file = os.path.join(TEMP_DIR, f"{pdb_id}_{display_score_type.lower()}_binding_site_residues.txt")with open(prediction_file, "w") as f:f.write(result_str)scored_pdb_name = os.path.join(TEMP_DIR, f"{pdb_id}_{segment}_{display_score_type.lower()}_predictions_scores.pdb")os.rename(scored_pdb, scored_pdb_name)# Clear memorydel structure, chain, protein_residues, scores_arrayreturn mol_vis, pymol_commands, [prediction_file, scored_pdb_name]finally:gc.collect()def fetch_interface(mode, pdb_id, pdb_file):if mode == "PDB ID":return fetch_pdb(pdb_id)elif mode == "Upload File":_, ext = os.path.splitext(pdb_file.name)file_path = os.path.join(TEMP_DIR, f"{os.path.basename(pdb_file.name)}")shutil.copy(pdb_file.name, file_path)if ext == '.cif':pdb_path = convert_cif_to_pdb(file_path, TEMP_DIR)else:pdb_path = file_pathreturn pdb_pathdef toggle_mode(selected_mode):1 unmodified linereturn gr.update(visible=True), gr.update(visible=False)else:return gr.update(visible=False), gr.update(visible=True)mode.change(toggle_mode,34 unmodified lines)def predict_utils(sequence):try:input_ids = tokenizer(" ".join(sequence), return_tensors="pt").input_ids.to(device)with torch.no_grad():outputs = model(input_ids).logitsoutputs_cpu = outputs.detach().cpu().numpy().squeeze()# Explicitly delete GPU tensorsdel outputs, input_idsif torch.cuda.is_available():torch.cuda.empty_cache()raw_scores = expit(outputs_cpu[:, 1] - outputs_cpu[:, 0])normalized_scores = normalize_scores(raw_scores)result = {"raw_scores": raw_scores.tolist(),"normalized_scores": normalized_scores.tolist()}# Clear memorydel outputs_cpu, raw_scores, normalized_scoresgc.collect()return resultexcept Exception as e:gc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()raise edummy_input = gr.Textbox(visible=False)dummy_output = gr.Textbox(visible=False)5 unmodified linesoutputs=[dummy_output])demo.launch(share=True)
10 unmodified lines111213141516262 unmodified lines2792802812822832842852862872882892902912922932942952962972982993003013023033043053 unmodified lines309310311312313314315316296 unmodified lines6136146156166176186196206217 unmodified lines62963063163263363463563663763863964010 unmodified linesimport osimport pandas as pdimport copyimport transformers, datasetsfrom transformers.modeling_outputs import TokenClassifierOutput262 unmodified lines# Load model and tokenizerif "ankh" in checkpoint :model = T5EncoderModel.from_pretrained(checkpoint,resume_download=True)tokenizer = AutoTokenizer.from_pretrained(checkpoint,resume_download=True)elif "prot_t5" in checkpoint:# possible to load the half precision model (thanks to @pawel-rezo for pointing that out)if half_precision and deepspeed:#tokenizer = T5Tokenizer.from_pretrained('Rostlab/prot_t5_xl_half_uniref50-enc', do_lower_case=False)#model = T5EncoderModel.from_pretrained("Rostlab/prot_t5_xl_half_uniref50-enc", torch_dtype=torch.float16)#.to(torch.device('cuda')tokenizer = T5Tokenizer.from_pretrained(checkpoint, do_lower_case=False,resume_download=True)model = T5EncoderModel.from_pretrained(checkpoint, torch_dtype=torch.float16).to(torch.device('cuda'),resume_download=True)else:model = T5EncoderModel.from_pretrained(checkpoint)tokenizer = T5Tokenizer.from_pretrained(checkpoint)elif "ProstT5" in checkpoint:if half_precision and deepspeed:tokenizer = T5Tokenizer.from_pretrained(checkpoint, do_lower_case=False,resume_download=True)model = T5EncoderModel.from_pretrained(checkpoint, torch_dtype=torch.float16).to(torch.device('cuda'),resume_download=True)else:model = T5EncoderModel.from_pretrained(checkpoint,resume_download=True)tokenizer = T5Tokenizer.from_pretrained(checkpoint,resume_download=True)# Create new Classifier model with PT5 dimensionsclass_config=ClassConfig(num_labels=num_labels)3 unmodified linesclass_model.shared=model.sharedclass_model.encoder=model.encoder# Delete the checkpoint modelmodel=class_modeldel class_modelif full == True:296 unmodified linesreturn model, tokenizerdef load_model(checkpoint,max_length):#checkpoint='ThorbenF/prot_t5_xl_uniref50'#best_model_path='ThorbenF/prot_t5_xl_uniref50/cpt.pth'full=Falsedeepspeed=Falsemixed=False7 unmodified lineselse:model, tokenizer = load_T5_model_classification(checkpoint, num_labels, mixed, full, deepspeed)# Download the filelocal_file = hf_hub_download(repo_id=checkpoint, filename="cpt.pth")# Load the best model statestate_dict = torch.load(local_file, map_location=torch.device('cpu'), weights_only=True)model.load_state_dict(state_dict)return model, tokenizer10 unmodified lines11121314151617262 unmodified lines2802812822832842852862872882892902912922932942952962972982993003013023033043 unmodified lines308309310311312313314315316317318319320296 unmodified lines6176186196206216226237 unmodified lines63163263363463563663763863964064164264364464564664710 unmodified linesimport osimport pandas as pdimport copyimport gcimport transformers, datasetsfrom transformers.modeling_outputs import TokenClassifierOutput262 unmodified lines# Load model and tokenizerif "ankh" in checkpoint :model = T5EncoderModel.from_pretrained(checkpoint, resume_download=True)tokenizer = AutoTokenizer.from_pretrained(checkpoint, resume_download=True)elif "prot_t5" in checkpoint:# possible to load the half precision model (thanks to @pawel-rezo for pointing that out)if half_precision and deepspeed:tokenizer = T5Tokenizer.from_pretrained(checkpoint, do_lower_case=False, resume_download=True)model = T5EncoderModel.from_pretrained(checkpoint, torch_dtype=torch.float16, resume_download=True).to(torch.device('cuda'))else:model = T5EncoderModel.from_pretrained(checkpoint, resume_download=True)tokenizer = T5Tokenizer.from_pretrained(checkpoint, resume_download=True)elif "ProstT5" in checkpoint:if half_precision and deepspeed:tokenizer = T5Tokenizer.from_pretrained(checkpoint, do_lower_case=False, resume_download=True)model = T5EncoderModel.from_pretrained(checkpoint, torch_dtype=torch.float16, resume_download=True).to(torch.device('cuda'))else:model = T5EncoderModel.from_pretrained(checkpoint, resume_download=True)tokenizer = T5Tokenizer.from_pretrained(checkpoint, resume_download=True)# Create new Classifier model with PT5 dimensionsclass_config=ClassConfig(num_labels=num_labels)3 unmodified linesclass_model.shared=model.sharedclass_model.encoder=model.encoder# Delete the checkpoint model and clear memorydel modelgc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()model = class_modeldel class_modelif full == True:296 unmodified linesreturn model, tokenizerdef load_model(checkpoint, max_length):full=Falsedeepspeed=Falsemixed=False7 unmodified lineselse:model, tokenizer = load_T5_model_classification(checkpoint, num_labels, mixed, full, deepspeed)# Download the filelocal_file = hf_hub_download(repo_id=checkpoint, filename="cpt.pth")# Load the best model state with memory mapping for efficiencystate_dict = torch.load(local_file, map_location=torch.device('cpu'), weights_only=True)model.load_state_dict(state_dict)# Clear state_dict from memory immediately after loadingdel state_dictgc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()return model, tokenizer
app.py+197-112
model_loader.py+26-19