steveyu323 commited on
Commit
e1bca72
·
verified ·
1 Parent(s): e686732

Upload folder using huggingface_hub

Browse files
.ipynb_checkpoints/config-checkpoint.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from modeling import KinaseSubstrateConfig, KinaseSubstrateModel
2
+ import torch
3
+
4
+ # Build config
5
+ config = KinaseSubstrateConfig(
6
+ tape_model_name="bert-base",
7
+ num_labels=2,
8
+ threshold=ckpt["threshold"], # from your checkpoint
9
+ with_sep=True,
10
+ max_len=1024,
11
+ # Tell HF where to find the custom classes:
12
+ auto_map={
13
+ "AutoConfig": "modeling.KinaseSubstrateConfig",
14
+ "AutoModel": "modeling.KinaseSubstrateModel",
15
+ },
16
+ custom_pipelines={
17
+ "kinase-substrate": {
18
+ "impl": "pipeline.KinaseSubstratePipeline",
19
+ "pt": ["AutoModel"],
20
+ }
21
+ },
22
+ )
23
+
24
+ # Build and load model
25
+ model = KinaseSubstrateModel(config)
26
+ model.backbone.load_state_dict(ckpt["state_dict"]) # load your trained weights
27
+
28
+ # Save
29
+ model.save_pretrained("./my_kinase_model")
30
+ config.save_pretrained("./my_kinase_model")
.ipynb_checkpoints/config_raw-checkpoint.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "attention_probs_dropout_prob": 0.1,
3
+ "base_model": "transformer",
4
+ "finetuning_task": null,
5
+ "hidden_act": "gelu",
6
+ "hidden_dropout_prob": 0.1,
7
+ "hidden_size": 768,
8
+ "initializer_range": 0.02,
9
+ "input_size": 768,
10
+ "intermediate_size": 3072,
11
+ "layer_norm_eps": 1e-12,
12
+ "max_position_embeddings": 8192,
13
+ "num_attention_heads": 12,
14
+ "num_hidden_layers": 12,
15
+ "num_labels": 2,
16
+ "output_attentions": false,
17
+ "output_hidden_states": false,
18
+ "output_size": 768,
19
+ "pruned_heads": {},
20
+ "torchscript": false,
21
+ "type_vocab_size": 1,
22
+ "vocab_size": 30
23
+ }
.ipynb_checkpoints/modeling-checkpoint.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PreTrainedModel, PretrainedConfig
2
+ import torch
3
+ import torch.nn as nn
4
+ from tape import ProteinBertForSequenceClassification, TAPETokenizer
5
+
6
+
7
+ class KinaseSubstrateConfig(PretrainedConfig):
8
+ model_type = "kinase_substrate_bert"
9
+
10
+ def __init__(
11
+ self,
12
+ tape_model_name="bert-base",
13
+ num_labels=2,
14
+ threshold=0.5,
15
+ with_sep=True,
16
+ max_len=1024,
17
+ **kwargs,
18
+ ):
19
+ super().__init__(**kwargs)
20
+ self.tape_model_name = tape_model_name
21
+ self.num_labels = num_labels
22
+ self.threshold = threshold
23
+ self.with_sep = with_sep
24
+ self.max_len = max_len
25
+
26
+
27
+ class KinaseSubstrateModel(PreTrainedModel):
28
+ config_class = KinaseSubstrateConfig
29
+
30
+ def __init__(self, config: KinaseSubstrateConfig):
31
+ super().__init__(config)
32
+ self.backbone = ProteinBertForSequenceClassification.from_pretrained(
33
+ config.tape_model_name, num_labels=config.num_labels
34
+ )
35
+
36
+ def forward(self, input_ids, input_mask=None, targets=None):
37
+ return self.backbone(
38
+ input_ids=input_ids,
39
+ input_mask=input_mask,
40
+ targets=targets,
41
+ )
42
+
43
+ def predict_proba(self, input_ids, input_mask):
44
+ self.eval()
45
+ with torch.no_grad():
46
+ (_, _), logits = self.forward(input_ids=input_ids, input_mask=input_mask)
47
+ return torch.softmax(logits, dim=-1)[:, 1]
.ipynb_checkpoints/pipeline-checkpoint.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import Pipeline
2
+ from tape import TAPETokenizer
3
+ import torch
4
+ import numpy as np
5
+
6
+
7
+ class KinaseSubstratePipeline(Pipeline):
8
+ """
9
+ Usage:
10
+ pipe = pipeline(
11
+ "kinase-substrate",
12
+ model="your-username/kinase-substrate-classifier",
13
+ trust_remote_code=True,
14
+ )
15
+ result = pipe({"kinase_seq": "MGSSHHH...", "substrate_seq": "ARTKQTAR..."})
16
+ """
17
+
18
+ def __init__(self, *args, **kwargs):
19
+ super().__init__(*args, **kwargs)
20
+ self.tape_tokenizer = TAPETokenizer(vocab="iupac")
21
+
22
+ def _sanitize_parameters(self, **kwargs):
23
+ return {}, {}, {}
24
+
25
+ def preprocess(self, inputs):
26
+ kinase_seq = inputs["kinase_seq"].upper().replace(" ", "")
27
+ substrate_seq = inputs["substrate_seq"].upper().replace(" ", "")
28
+
29
+ cfg = self.model.config
30
+ kin_toks = self.tape_tokenizer.tokenize(kinase_seq)
31
+ sub_toks = self.tape_tokenizer.tokenize(substrate_seq)
32
+ toks = kin_toks + (["<sep>"] if cfg.with_sep else []) + sub_toks
33
+ toks = self.tape_tokenizer.add_special_tokens(toks)
34
+ ids = self.tape_tokenizer.convert_tokens_to_ids(toks)[: cfg.max_len]
35
+
36
+ input_ids = torch.tensor([ids], dtype=torch.long)
37
+ input_mask = torch.ones_like(input_ids)
38
+
39
+ return {"input_ids": input_ids, "input_mask": input_mask}
40
+
41
+ def _forward(self, model_inputs):
42
+ prob = self.model.predict_proba(
43
+ input_ids=model_inputs["input_ids"].to(self.device),
44
+ input_mask=model_inputs["input_mask"].to(self.device),
45
+ )
46
+ return {"prob": prob.cpu().numpy()}
47
+
48
+ def postprocess(self, model_outputs):
49
+ prob = float(model_outputs["prob"][0])
50
+ threshold = self.model.config.threshold
51
+ return {
52
+ "probability": round(prob, 4),
53
+ "label": "interaction" if prob >= threshold else "no_interaction",
54
+ "threshold": threshold,
55
+ }
config.json CHANGED
@@ -1,23 +1,30 @@
1
- {
2
- "attention_probs_dropout_prob": 0.1,
3
- "base_model": "transformer",
4
- "finetuning_task": null,
5
- "hidden_act": "gelu",
6
- "hidden_dropout_prob": 0.1,
7
- "hidden_size": 768,
8
- "initializer_range": 0.02,
9
- "input_size": 768,
10
- "intermediate_size": 3072,
11
- "layer_norm_eps": 1e-12,
12
- "max_position_embeddings": 8192,
13
- "num_attention_heads": 12,
14
- "num_hidden_layers": 12,
15
- "num_labels": 2,
16
- "output_attentions": false,
17
- "output_hidden_states": false,
18
- "output_size": 768,
19
- "pruned_heads": {},
20
- "torchscript": false,
21
- "type_vocab_size": 1,
22
- "vocab_size": 30
23
- }
 
 
 
 
 
 
 
 
1
+ from modeling import KinaseSubstrateConfig, KinaseSubstrateModel
2
+ import torch
3
+
4
+ # Build config
5
+ config = KinaseSubstrateConfig(
6
+ tape_model_name="bert-base",
7
+ num_labels=2,
8
+ threshold=ckpt["threshold"], # from your checkpoint
9
+ with_sep=True,
10
+ max_len=1024,
11
+ # Tell HF where to find the custom classes:
12
+ auto_map={
13
+ "AutoConfig": "modeling.KinaseSubstrateConfig",
14
+ "AutoModel": "modeling.KinaseSubstrateModel",
15
+ },
16
+ custom_pipelines={
17
+ "kinase-substrate": {
18
+ "impl": "pipeline.KinaseSubstratePipeline",
19
+ "pt": ["AutoModel"],
20
+ }
21
+ },
22
+ )
23
+
24
+ # Build and load model
25
+ model = KinaseSubstrateModel(config)
26
+ model.backbone.load_state_dict(ckpt["state_dict"]) # load your trained weights
27
+
28
+ # Save
29
+ model.save_pretrained("./my_kinase_model")
30
+ config.save_pretrained("./my_kinase_model")
config_raw.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "attention_probs_dropout_prob": 0.1,
3
+ "base_model": "transformer",
4
+ "finetuning_task": null,
5
+ "hidden_act": "gelu",
6
+ "hidden_dropout_prob": 0.1,
7
+ "hidden_size": 768,
8
+ "initializer_range": 0.02,
9
+ "input_size": 768,
10
+ "intermediate_size": 3072,
11
+ "layer_norm_eps": 1e-12,
12
+ "max_position_embeddings": 8192,
13
+ "num_attention_heads": 12,
14
+ "num_hidden_layers": 12,
15
+ "num_labels": 2,
16
+ "output_attentions": false,
17
+ "output_hidden_states": false,
18
+ "output_size": 768,
19
+ "pruned_heads": {},
20
+ "torchscript": false,
21
+ "type_vocab_size": 1,
22
+ "vocab_size": 30
23
+ }
modeling.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PreTrainedModel, PretrainedConfig
2
+ import torch
3
+ import torch.nn as nn
4
+ from tape import ProteinBertForSequenceClassification, TAPETokenizer
5
+
6
+
7
+ class KinaseSubstrateConfig(PretrainedConfig):
8
+ model_type = "kinase_substrate_bert"
9
+
10
+ def __init__(
11
+ self,
12
+ tape_model_name="bert-base",
13
+ num_labels=2,
14
+ threshold=0.5,
15
+ with_sep=True,
16
+ max_len=1024,
17
+ **kwargs,
18
+ ):
19
+ super().__init__(**kwargs)
20
+ self.tape_model_name = tape_model_name
21
+ self.num_labels = num_labels
22
+ self.threshold = threshold
23
+ self.with_sep = with_sep
24
+ self.max_len = max_len
25
+
26
+
27
+ class KinaseSubstrateModel(PreTrainedModel):
28
+ config_class = KinaseSubstrateConfig
29
+
30
+ def __init__(self, config: KinaseSubstrateConfig):
31
+ super().__init__(config)
32
+ self.backbone = ProteinBertForSequenceClassification.from_pretrained(
33
+ config.tape_model_name, num_labels=config.num_labels
34
+ )
35
+
36
+ def forward(self, input_ids, input_mask=None, targets=None):
37
+ return self.backbone(
38
+ input_ids=input_ids,
39
+ input_mask=input_mask,
40
+ targets=targets,
41
+ )
42
+
43
+ def predict_proba(self, input_ids, input_mask):
44
+ self.eval()
45
+ with torch.no_grad():
46
+ (_, _), logits = self.forward(input_ids=input_ids, input_mask=input_mask)
47
+ return torch.softmax(logits, dim=-1)[:, 1]
pipeline.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import Pipeline
2
+ from tape import TAPETokenizer
3
+ import torch
4
+ import numpy as np
5
+
6
+
7
+ class KinaseSubstratePipeline(Pipeline):
8
+ """
9
+ Usage:
10
+ pipe = pipeline(
11
+ "kinase-substrate",
12
+ model="your-username/kinase-substrate-classifier",
13
+ trust_remote_code=True,
14
+ )
15
+ result = pipe({"kinase_seq": "MGSSHHH...", "substrate_seq": "ARTKQTAR..."})
16
+ """
17
+
18
+ def __init__(self, *args, **kwargs):
19
+ super().__init__(*args, **kwargs)
20
+ self.tape_tokenizer = TAPETokenizer(vocab="iupac")
21
+
22
+ def _sanitize_parameters(self, **kwargs):
23
+ return {}, {}, {}
24
+
25
+ def preprocess(self, inputs):
26
+ kinase_seq = inputs["kinase_seq"].upper().replace(" ", "")
27
+ substrate_seq = inputs["substrate_seq"].upper().replace(" ", "")
28
+
29
+ cfg = self.model.config
30
+ kin_toks = self.tape_tokenizer.tokenize(kinase_seq)
31
+ sub_toks = self.tape_tokenizer.tokenize(substrate_seq)
32
+ toks = kin_toks + (["<sep>"] if cfg.with_sep else []) + sub_toks
33
+ toks = self.tape_tokenizer.add_special_tokens(toks)
34
+ ids = self.tape_tokenizer.convert_tokens_to_ids(toks)[: cfg.max_len]
35
+
36
+ input_ids = torch.tensor([ids], dtype=torch.long)
37
+ input_mask = torch.ones_like(input_ids)
38
+
39
+ return {"input_ids": input_ids, "input_mask": input_mask}
40
+
41
+ def _forward(self, model_inputs):
42
+ prob = self.model.predict_proba(
43
+ input_ids=model_inputs["input_ids"].to(self.device),
44
+ input_mask=model_inputs["input_mask"].to(self.device),
45
+ )
46
+ return {"prob": prob.cpu().numpy()}
47
+
48
+ def postprocess(self, model_outputs):
49
+ prob = float(model_outputs["prob"][0])
50
+ threshold = self.model.config.threshold
51
+ return {
52
+ "probability": round(prob, 4),
53
+ "label": "interaction" if prob >= threshold else "no_interaction",
54
+ "threshold": threshold,
55
+ }