Views
No views yet
microsoft/deberta-v3-large model serves as the foundation. This model utilizes DeBERTa (Decoding-enhanced BERT with disentangled attention), an improved version of BERT and RoBERTa, which incorporates disentangled attention and enhanced mask decoder for better performance.transformers library:1import torch
2import torch.nn as nn
3from transformers import AutoTokenizer, AutoConfig, AutoModel, PreTrainedModel
4
5class DesklibAIDetectionModel(PreTrainedModel):
6 config_class = AutoConfig
7
8 def __init__(self, config):
9 super().__init__(config)
10 # Initialize the base transformer model.
11 self.model = AutoModel.from_config(config)
12 # Define a classifier head.
13 self.classifier = nn.Linear(config.hidden_size, 1)
14 # Initialize weights (handled by PreTrainedModel)
15 self.init_weights()
16
17 def forward(self, input_ids, attention_mask=None, labels=None):
18 # Forward pass through the transformer
19 outputs = self.model(input_ids, attention_mask=attention_mask)
20 last_hidden_state = outputs[0]
21 # Mean pooling
22 input_mask_expanded = attention_mask.unsqueeze(-1).expand(last_hidden_state.size()).float()
23 sum_embeddings = torch.sum(last_hidden_state * input_mask_expanded, dim=1)
24 sum_mask = torch.clamp(input_mask_expanded.sum(dim=1), min=1e-9)
25 pooled_output = sum_embeddings / sum_mask
26
27 # Classifier
28 logits = self.classifier(pooled_output)
29 loss = None
30 if labels is not None:
31 loss_fct = nn.BCEWithLogitsLoss()
32 loss = loss_fct(logits.view(-1), labels.float())
33
34 output = {"logits": logits}
35 if loss is not None:
36 output["loss"] = loss
37 return output
38
39def predict_single_text(text, model, tokenizer, device, max_len=768, threshold=0.5):
40 encoded = tokenizer(
41 text,
42 padding='max_length',
43 truncation=True,
44 max_length=max_len,
45 return_tensors='pt'
46 )
47 input_ids = encoded['input_ids'].to(device)
48 attention_mask = encoded['attention_mask'].to(device)
49
50 model.eval()
51 with torch.no_grad():
52 outputs = model(input_ids=input_ids, attention_mask=attention_mask)
53 logits = outputs["logits"]
54 probability = torch.sigmoid(logits).item()
55
56 label = 1 if probability >= threshold else 0
57 return probability, label
58
59def main():
60 # --- Model and Tokenizer Directory ---
61 model_directory = "desklib/ai-text-detector-v1.01"
62
63 # --- Load tokenizer and model ---
64 tokenizer = AutoTokenizer.from_pretrained(model_directory)
65 model = DesklibAIDetectionModel.from_pretrained(model_directory)
66
67 # --- Set up device ---
68 device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
69 model.to(device)
70
71 # --- Example Input text ---
72 text_ai = "AI detection refers to the process of identifying whether a given piece of content, such as text, images, or audio, has been generated by artificial intelligence. This is achieved using various machine learning techniques, including perplexity analysis, entropy measurements, linguistic pattern recognition, and neural network classifiers trained on human and AI-generated data. Advanced AI detection tools assess writing style, coherence, and statistical properties to determine the likelihood of AI involvement. These tools are widely used in academia, journalism, and content moderation to ensure originality, prevent misinformation, and maintain ethical standards. As AI-generated content becomes increasingly sophisticated, AI detection methods continue to evolve, integrating deep learning models and ensemble techniques for improved accuracy."
73 text_human = "It is estimated that a major part of the content in the internet will be generated by AI / LLMs by 2025. This leads to a lot of misinformation and credibility related issues. That is why if is important to have accurate tools to identify if a content is AI generated or human written"
74
75 # --- Run prediction ---
76 probability, predicted_label = predict_single_text(text_ai, model, tokenizer, device)
77 print(f"Probability of being AI generated: {probability:.4f}")
78 print(f"Predicted label: {'AI Generated' if predicted_label == 1 else 'Not AI Generated'}")
79
80 probability, predicted_label = predict_single_text(text_human, model, tokenizer, device)
81 print(f"Probability of being AI generated: {probability:.4f}")
82 print(f"Predicted label: {'AI Generated' if predicted_label == 1 else 'Not AI Generated'}")
83
84if __name__ == "__main__":
85 main()