Text Classification
Safetensors
deberta-v2

Package model correctly

#2
by tcapelle - opened
README.md CHANGED
@@ -33,15 +33,14 @@ For more detailed code regarding generating the annotations in Toxic Commons, tr
33
 
34
  # How to Use
35
 
36
- ```
37
- from transformers import AutoTokenizer
38
- from celadon.model import MultiHeadDebertaForSequenceClassification
39
 
40
- tokenizer = AutoTokenizer.from_pretrained("celadon")
41
- model = MultiHeadDebertaForSequenceClassification.from_pretrained("celadon")
42
  model.eval()
43
 
44
- sample_text = "This is an example of a normal sentence"
45
 
46
  inputs = tokenizer(sample_text, return_tensors="pt", padding=True, truncation=True)
47
  outputs = model(input_ids=inputs['input_ids'], attention_mask=inputs['attention_mask'])
@@ -53,6 +52,22 @@ predictions = outputs.argmax(dim=-1).squeeze().tolist()
53
  print(f"Text: {sample_text}")
54
  for i, category in enumerate(categories):
55
  print(f"Prediction for Category {category}: {predictions[i]}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  ```
57
 
58
  # How to Cite
 
33
 
34
  # How to Use
35
 
36
+ ```py
37
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
 
38
 
39
+ model = AutoModelForSequenceClassification.from_pretrained("PleIAs/celadon", trust_remote_code=True)
40
+ tokenizer = AutoTokenizer.from_pretrained("PleIAs/celadon", trust_remote_code=True)
41
  model.eval()
42
 
43
+ sample_text = "A very gender inappropriate comment"
44
 
45
  inputs = tokenizer(sample_text, return_tensors="pt", padding=True, truncation=True)
46
  outputs = model(input_ids=inputs['input_ids'], attention_mask=inputs['attention_mask'])
 
52
  print(f"Text: {sample_text}")
53
  for i, category in enumerate(categories):
54
  print(f"Prediction for Category {category}: {predictions[i]}")
55
+ # Text: A very gender inappropriate comment
56
+ # Prediction for Category Race/Origin: 0
57
+ # Prediction for Category Gender/Sex: 3
58
+ # Prediction for Category Religion: 0
59
+ # Prediction for Category Ability: 0
60
+ # Prediction for Category Violence: 0
61
+ ```
62
+
63
+ you can also use transformers pipelines to get a more streamlined experience
64
+
65
+ ```py
66
+ from transformers import pipeline
67
+ pipe = pipeline("text-classification", model="PleIAs/celadon", trust_remote_code=True)
68
+ result = pipe("This is an example of a normal sentence")
69
+ print(result)
70
+ # [{'Race/Origin': 0, 'Gender/Sex': 3, 'Religion': 0, 'Ability': 0, 'Violence': 0}]
71
  ```
72
 
73
  # How to Cite
config.json CHANGED
@@ -1,8 +1,22 @@
1
  {
 
2
  "architectures": [
3
- "MultiHeadDebertaForSequenceClassification"
4
  ],
5
  "attention_probs_dropout_prob": 0.1,
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  "hidden_act": "gelu",
7
  "hidden_dropout_prob": 0.1,
8
  "hidden_size": 768,
@@ -11,9 +25,10 @@
11
  "layer_norm_eps": 1e-07,
12
  "max_position_embeddings": 512,
13
  "max_relative_positions": -1,
14
- "model_type": "deberta-v2",
15
  "norm_rel_ebd": "layer_norm",
16
  "num_attention_heads": 12,
 
17
  "num_hidden_layers": 6,
18
  "pad_token_id": 0,
19
  "pooler_dropout": 0,
@@ -28,7 +43,7 @@
28
  "relative_attention": true,
29
  "share_att_key": true,
30
  "torch_dtype": "float32",
31
- "transformers_version": "4.45.2",
32
  "type_vocab_size": 0,
33
  "vocab_size": 128100
34
  }
 
1
  {
2
+ "_name_or_path": "./celadon",
3
  "architectures": [
4
+ "MultiHeadDebertaForSequenceClassificationModel"
5
  ],
6
  "attention_probs_dropout_prob": 0.1,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_deberta_multi.MultiHeadDebertaV2Config",
9
+ "AutoModelForSequenceClassification": "modelling_deberta_multi.MultiHeadDebertaForSequenceClassificationModel"
10
+ },
11
+ "custom_pipelines": {
12
+ "text-classification": {
13
+ "impl": "custom_pipeline.CustomTextClassificationPipeline",
14
+ "pt": [
15
+ "AutoModelForSequenceClassification"
16
+ ],
17
+ "tf": []
18
+ }
19
+ },
20
  "hidden_act": "gelu",
21
  "hidden_dropout_prob": 0.1,
22
  "hidden_size": 768,
 
25
  "layer_norm_eps": 1e-07,
26
  "max_position_embeddings": 512,
27
  "max_relative_positions": -1,
28
+ "model_type": "multi-head-deberta-for-sequence-classification",
29
  "norm_rel_ebd": "layer_norm",
30
  "num_attention_heads": 12,
31
+ "num_heads": 5,
32
  "num_hidden_layers": 6,
33
  "pad_token_id": 0,
34
  "pooler_dropout": 0,
 
43
  "relative_attention": true,
44
  "share_att_key": true,
45
  "torch_dtype": "float32",
46
+ "transformers_version": "4.46.2",
47
  "type_vocab_size": 0,
48
  "vocab_size": 128100
49
  }
configuration_deberta_multi.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from transformers import DebertaV2Config
2
+
3
+ class MultiHeadDebertaV2Config(DebertaV2Config):
4
+ model_type = "multi-head-deberta-for-sequence-classification"
5
+ def __init__(self, num_heads=5, **kwargs):
6
+ self.num_heads = num_heads
7
+ super().__init__(**kwargs)
custom_pipeline.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import TextClassificationPipeline, AutoTokenizer
2
+
3
+ class CustomTextClassificationPipeline(TextClassificationPipeline):
4
+ def __init__(self, model, tokenizer=None, **kwargs):
5
+ # Initialize tokenizer first
6
+ if tokenizer is None:
7
+ tokenizer = AutoTokenizer.from_pretrained(model.config._name_or_path)
8
+ # Make sure we store the tokenizer before calling super().__init__
9
+ self.tokenizer = tokenizer
10
+ super().__init__(model=model, tokenizer=tokenizer, **kwargs)
11
+
12
+ def _sanitize_parameters(self, **kwargs):
13
+ preprocess_kwargs = {}
14
+ return preprocess_kwargs, {}, {}
15
+
16
+ def preprocess(self, inputs):
17
+ return self.tokenizer(inputs, return_tensors='pt', truncation=False)
18
+
19
+ def _forward(self, model_inputs):
20
+ input_ids = model_inputs['input_ids']
21
+ attention_mask = (input_ids != 0).long()
22
+ outputs = self.model(input_ids=input_ids, attention_mask=attention_mask)
23
+ return outputs
24
+
25
+ def postprocess(self, model_outputs):
26
+ predictions = model_outputs.logits.argmax(dim=-1).squeeze().tolist()
27
+ categories = ["Race/Origin", "Gender/Sex", "Religion", "Ability", "Violence", "Other"]
28
+ return dict(zip(categories, predictions))
29
+
model.py DELETED
@@ -1,20 +0,0 @@
1
- import torch
2
- import torch.nn as nn
3
- from transformers import DebertaV2Model, DebertaV2PreTrainedModel
4
-
5
- class MultiHeadDebertaForSequenceClassification(DebertaV2PreTrainedModel):
6
- def __init__(self, config, num_heads=5):
7
- super().__init__(config)
8
- self.num_heads = num_heads
9
- self.deberta = DebertaV2Model(config)
10
- self.heads = nn.ModuleList([nn.Linear(config.hidden_size, 4) for _ in range(num_heads)])
11
- self.dropout = nn.Dropout(config.hidden_dropout_prob)
12
- self.post_init()
13
-
14
- def forward(self, input_ids=None, attention_mask=None):
15
- outputs = self.deberta(input_ids=input_ids, attention_mask=attention_mask)
16
- sequence_output = outputs[0]
17
- logits_list = [head(self.dropout(sequence_output[:, 0, :])) for head in self.heads]
18
- logits = torch.stack(logits_list, dim=1)
19
- return logits
20
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
modelling_deberta_multi.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn, Tensor
3
+ from typing import Optional
4
+ from transformers import DebertaV2PreTrainedModel, DebertaV2Model
5
+ from .configuration_deberta_multi import MultiHeadDebertaV2Config
6
+
7
+ class MultiHeadDebertaForSequenceClassificationModel(DebertaV2PreTrainedModel):
8
+
9
+ config_class = MultiHeadDebertaV2Config
10
+ def __init__(self, config): # type: ignore
11
+ super().__init__(config)
12
+ self.deberta = DebertaV2Model(config)
13
+ self.heads = nn.ModuleList(
14
+ [nn.Linear(config.hidden_size, 4) for _ in range(config.num_heads)]
15
+ )
16
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
17
+ self.post_init()
18
+
19
+ def forward(
20
+ self,
21
+ input_ids: Optional["Tensor"] = None,
22
+ attention_mask: Optional["Tensor"] = None,
23
+ ) -> "Tensor":
24
+ outputs = self.deberta(input_ids=input_ids, attention_mask=attention_mask)
25
+ sequence_output = outputs[0]
26
+ logits_list = [
27
+ head(self.dropout(sequence_output[:, 0, :])) for head in self.heads
28
+ ]
29
+ logits = torch.stack(logits_list, dim=1)
30
+ outputs["logits"] = logits
31
+ return outputs
special_tokens_map.json CHANGED
@@ -1,10 +1,46 @@
1
  {
2
- "bos_token": "[CLS]",
3
- "cls_token": "[CLS]",
4
- "eos_token": "[SEP]",
5
- "mask_token": "[MASK]",
6
- "pad_token": "[PAD]",
7
- "sep_token": "[SEP]",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  "unk_token": {
9
  "content": "[UNK]",
10
  "lstrip": false,
 
1
  {
2
+ "bos_token": {
3
+ "content": "[CLS]",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "cls_token": {
10
+ "content": "[CLS]",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "eos_token": {
17
+ "content": "[SEP]",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "mask_token": {
24
+ "content": "[MASK]",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "pad_token": {
31
+ "content": "[PAD]",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ },
37
+ "sep_token": {
38
+ "content": "[SEP]",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false
43
+ },
44
  "unk_token": {
45
  "content": "[UNK]",
46
  "lstrip": false,
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json CHANGED
@@ -47,12 +47,19 @@
47
  "do_lower_case": false,
48
  "eos_token": "[SEP]",
49
  "mask_token": "[MASK]",
50
- "model_max_length": 1000000000000000019884624838656,
 
 
51
  "pad_token": "[PAD]",
 
 
52
  "sep_token": "[SEP]",
53
  "sp_model_kwargs": {},
54
  "split_by_punct": false,
 
55
  "tokenizer_class": "DebertaV2Tokenizer",
 
 
56
  "unk_token": "[UNK]",
57
  "vocab_type": "spm"
58
  }
 
47
  "do_lower_case": false,
48
  "eos_token": "[SEP]",
49
  "mask_token": "[MASK]",
50
+ "max_length": 512,
51
+ "model_max_length": 512,
52
+ "pad_to_multiple_of": null,
53
  "pad_token": "[PAD]",
54
+ "pad_token_type_id": 0,
55
+ "padding_side": "right",
56
  "sep_token": "[SEP]",
57
  "sp_model_kwargs": {},
58
  "split_by_punct": false,
59
+ "stride": 0,
60
  "tokenizer_class": "DebertaV2Tokenizer",
61
+ "truncation_side": "right",
62
+ "truncation_strategy": "longest_first",
63
  "unk_token": "[UNK]",
64
  "vocab_type": "spm"
65
  }