yushize commited on
Commit
e6c3762
·
verified ·
1 Parent(s): f7bcbc4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -8
app.py CHANGED
@@ -11,7 +11,13 @@ from typing import Dict, List, Optional, Tuple
11
 
12
  import gradio as gr
13
  import torch
14
- from transformers import AutoModel, AutoTokenizer, T5EncoderModel, T5Tokenizer
 
 
 
 
 
 
15
 
16
  APP_TITLE = "Protein Embedding"
17
 
@@ -252,12 +258,16 @@ class SingleModelRunner:
252
  from esm.models.esmc import ESMC
253
  self.model = ESMC.from_pretrained(spec.model_id).to(target_device)
254
  self.model.eval()
 
255
 
256
  elif spec.family == "prosst":
257
  ensure_prosst_repo()
258
 
259
- self.tokenizer = AutoTokenizer.from_pretrained(spec.tokenizer_id, trust_remote_code=True)
260
- self.model = AutoModel.from_pretrained(
 
 
 
261
  spec.model_id,
262
  trust_remote_code=True,
263
  output_hidden_states=True,
@@ -289,6 +299,7 @@ def embed_hf_encoder(seq: str) -> torch.Tensor:
289
  truncation=False,
290
  )
291
  enc = {k: v.to(RUNNER.device) for k, v in enc.items()}
 
292
  out = RUNNER.model(**{k: v for k, v in enc.items() if k != "special_tokens_mask"})
293
  hidden = out.last_hidden_state[0]
294
 
@@ -312,6 +323,7 @@ def embed_t5_encoder(seq: str) -> torch.Tensor:
312
  truncation=False,
313
  )
314
  enc = {k: v.to(RUNNER.device) for k, v in enc.items()}
 
315
  out = RUNNER.model(**{k: v for k, v in enc.items() if k != "special_tokens_mask"})
316
  hidden = out.last_hidden_state[0]
317
 
@@ -354,9 +366,12 @@ def embed_esmc(seq: str) -> torch.Tensor:
354
  raise ValueError(f"ESMC returned shape {tuple(emb.shape)} for sequence length {len(seq)}.")
355
 
356
 
357
- def get_sst_tokens(seq: str):
358
  sst = RUNNER.sst_predictor.predict(seq)
359
 
 
 
 
360
  if isinstance(sst, str):
361
  tokens = [int(x) for x in sst.strip().split()]
362
  elif isinstance(sst, torch.Tensor):
@@ -372,7 +387,6 @@ def get_sst_tokens(seq: str):
372
 
373
  tokens = [int(x) for x in tokens]
374
 
375
- # 尽量规整到 L
376
  if len(tokens) == len(seq) + 2:
377
  tokens = tokens[1:-1]
378
  elif len(tokens) == len(seq) + 1:
@@ -383,6 +397,9 @@ def get_sst_tokens(seq: str):
383
  if len(tokens) != len(seq):
384
  raise ValueError(f"SST token length mismatch: got {len(tokens)}, expected {len(seq)}")
385
 
 
 
 
386
  return tokens
387
 
388
 
@@ -400,8 +417,6 @@ def embed_prosst(seq: str) -> Tuple[torch.Tensor, List[int]]:
400
  )
401
  seq_enc = {k: v.to(RUNNER.device) for k, v in seq_enc.items()}
402
 
403
- # ProSST 常见做法是把结构 token 当作额外输入 ids
404
- # 这里直接构建 [1, L] LongTensor
405
  sst_ids = torch.tensor([sst_tokens], dtype=torch.long, device=RUNNER.device)
406
 
407
  tried = []
@@ -411,9 +426,15 @@ def embed_prosst(seq: str) -> Tuple[torch.Tensor, List[int]]:
411
  input_ids=seq_enc["input_ids"],
412
  attention_mask=seq_enc.get("attention_mask", None),
413
  output_hidden_states=True,
 
414
  **{kw: sst_ids},
415
  )
 
 
 
 
416
  hidden = out.hidden_states[-1][0]
 
417
  emb = normalize_to_Ld(
418
  hidden=hidden,
419
  expected_len=len(seq),
@@ -421,10 +442,13 @@ def embed_prosst(seq: str) -> Tuple[torch.Tensor, List[int]]:
421
  attention_mask=seq_enc.get("attention_mask", None)[0] if seq_enc.get("attention_mask", None) is not None else None,
422
  )
423
  return emb.detach().cpu().float(), sst_tokens
 
424
  except Exception as e:
425
  tried.append(f"{kw}: {repr(e)}")
426
 
427
- raise RuntimeError("Failed to run ProSST with known structure-token arg names: " + " | ".join(tried))
 
 
428
 
429
 
430
  def embed_one_sequence(seq: str):
 
11
 
12
  import gradio as gr
13
  import torch
14
+ from transformers import (
15
+ AutoModel,
16
+ AutoModelForMaskedLM,
17
+ AutoTokenizer,
18
+ T5EncoderModel,
19
+ T5Tokenizer,
20
+ )
21
 
22
  APP_TITLE = "Protein Embedding"
23
 
 
258
  from esm.models.esmc import ESMC
259
  self.model = ESMC.from_pretrained(spec.model_id).to(target_device)
260
  self.model.eval()
261
+ self.tokenizer = None
262
 
263
  elif spec.family == "prosst":
264
  ensure_prosst_repo()
265
 
266
+ self.tokenizer = AutoTokenizer.from_pretrained(
267
+ spec.tokenizer_id,
268
+ trust_remote_code=True,
269
+ )
270
+ self.model = AutoModelForMaskedLM.from_pretrained(
271
  spec.model_id,
272
  trust_remote_code=True,
273
  output_hidden_states=True,
 
299
  truncation=False,
300
  )
301
  enc = {k: v.to(RUNNER.device) for k, v in enc.items()}
302
+
303
  out = RUNNER.model(**{k: v for k, v in enc.items() if k != "special_tokens_mask"})
304
  hidden = out.last_hidden_state[0]
305
 
 
323
  truncation=False,
324
  )
325
  enc = {k: v.to(RUNNER.device) for k, v in enc.items()}
326
+
327
  out = RUNNER.model(**{k: v for k, v in enc.items() if k != "special_tokens_mask"})
328
  hidden = out.last_hidden_state[0]
329
 
 
366
  raise ValueError(f"ESMC returned shape {tuple(emb.shape)} for sequence length {len(seq)}.")
367
 
368
 
369
+ def get_sst_tokens(seq: str) -> List[int]:
370
  sst = RUNNER.sst_predictor.predict(seq)
371
 
372
+ print("SST raw type:", type(sst))
373
+ print("SST raw repr:", repr(sst)[:500])
374
+
375
  if isinstance(sst, str):
376
  tokens = [int(x) for x in sst.strip().split()]
377
  elif isinstance(sst, torch.Tensor):
 
387
 
388
  tokens = [int(x) for x in tokens]
389
 
 
390
  if len(tokens) == len(seq) + 2:
391
  tokens = tokens[1:-1]
392
  elif len(tokens) == len(seq) + 1:
 
397
  if len(tokens) != len(seq):
398
  raise ValueError(f"SST token length mismatch: got {len(tokens)}, expected {len(seq)}")
399
 
400
+ print("SST final length:", len(tokens))
401
+ print("SST first 30:", tokens[:30])
402
+
403
  return tokens
404
 
405
 
 
417
  )
418
  seq_enc = {k: v.to(RUNNER.device) for k, v in seq_enc.items()}
419
 
 
 
420
  sst_ids = torch.tensor([sst_tokens], dtype=torch.long, device=RUNNER.device)
421
 
422
  tried = []
 
426
  input_ids=seq_enc["input_ids"],
427
  attention_mask=seq_enc.get("attention_mask", None),
428
  output_hidden_states=True,
429
+ return_dict=True,
430
  **{kw: sst_ids},
431
  )
432
+
433
+ if getattr(out, "hidden_states", None) is None:
434
+ raise RuntimeError("ProSST output has no hidden_states")
435
+
436
  hidden = out.hidden_states[-1][0]
437
+
438
  emb = normalize_to_Ld(
439
  hidden=hidden,
440
  expected_len=len(seq),
 
442
  attention_mask=seq_enc.get("attention_mask", None)[0] if seq_enc.get("attention_mask", None) is not None else None,
443
  )
444
  return emb.detach().cpu().float(), sst_tokens
445
+
446
  except Exception as e:
447
  tried.append(f"{kw}: {repr(e)}")
448
 
449
+ raise RuntimeError(
450
+ "Failed to run ProSST with known structure-token arg names: " + " | ".join(tried)
451
+ )
452
 
453
 
454
  def embed_one_sequence(seq: str):