assix-research commited on
Commit
5534cd7
·
verified ·
1 Parent(s): fd5ffd9

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +89 -0
  2. inference.py +84 -0
  3. source_code_classifier.pth +3 -0
README.md CHANGED
@@ -1,3 +1,92 @@
1
  ---
2
  license: mit
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: mit
3
+ language:
4
+ - en
5
+ - code
6
+ pipeline_tag: text-classification
7
+ tags:
8
+ - pytorch
9
+ - code-classification
10
+ - transformer
11
+ - slm
12
  ---
13
+
14
+ # SourceCodeAuthorCheck-SLM-10M
15
+
16
+ A ~10 million parameter Small Language Model (SLM) Transformer designed for binary classification to detect whether Python source code was written by a human or generated by AI.
17
+
18
+ The model was trained on a dataset of human-written code extracted from GitHub (Q3 2017 and prior) and synthetic AI-generated code mimicking Q3 2026 generative AI paradigms.
19
+
20
+ ## Model Details
21
+ * **Architecture:** Custom PyTorch TransformerEncoder (4 layers, 8 heads, 128 d_model)
22
+ * **Parameters:** ~9.6M
23
+ * **Tokenizer:** GPT-2 (`gpt2`)
24
+ * **Hardware:** Trained on NVIDIA DGX Spark (Grace Blackwell) using mixed precision (bfloat16)
25
+
26
+ ## Usage
27
+
28
+ You will need the model class definition to load the weights.
29
+
30
+ ```python
31
+ import torch
32
+ import torch.nn as nn
33
+ from transformers import AutoTokenizer
34
+
35
+ class SourceCodeAuthorCheck(nn.Module):
36
+ def __init__(self, vocab_size=50257, d_model=128, nhead=8, num_layers=4, dim_feedforward=512):
37
+ super().__init__()
38
+ self.embedding = nn.Embedding(vocab_size, d_model)
39
+ self.pos_encoder = nn.Parameter(torch.zeros(1, 1024, d_model))
40
+
41
+ encoder_layers = nn.TransformerEncoderLayer(
42
+ d_model=d_model, nhead=nhead, dim_feedforward=dim_feedforward, batch_first=True
43
+ )
44
+ self.transformer = nn.TransformerEncoder(encoder_layers, num_layers=num_layers)
45
+ self.fc = nn.Linear(d_model, 1)
46
+
47
+ def forward(self, input_ids, attention_mask):
48
+ seq_len = input_ids.size(1)
49
+ x = self.embedding(input_ids) + self.pos_encoder[:, :seq_len, :]
50
+
51
+ src_key_padding_mask = ~attention_mask.bool()
52
+ x = self.transformer(x, src_key_padding_mask=src_key_padding_mask)
53
+
54
+ mask_expanded = attention_mask.unsqueeze(-1).float()
55
+ sum_embeddings = torch.sum(x * mask_expanded, 1)
56
+ sum_mask = torch.clamp(mask_expanded.sum(1), min=1e-9)
57
+ pooled = sum_embeddings / sum_mask
58
+
59
+ return self.fc(pooled)
60
+
61
+ # 1. Load Tokenizer and Model
62
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
63
+ tokenizer = AutoTokenizer.from_pretrained("gpt2")
64
+ tokenizer.pad_token = tokenizer.eos_token
65
+
66
+ model = SourceCodeAuthorCheck().to(device)
67
+ model.load_state_dict(torch.load("source_code_classifier.pth", map_location=device, weights_only=True))
68
+ model.eval()
69
+
70
+ # 2. Prepare Input
71
+ code_snippet = """
72
+ def hello_world():
73
+ print("Hello from 2015!")
74
+ """
75
+
76
+ inputs = tokenizer(
77
+ code_snippet,
78
+ return_tensors="pt",
79
+ truncation=True,
80
+ padding="max_length",
81
+ max_length=1024
82
+ ).to(device)
83
+
84
+ # 3. Inference
85
+ with torch.no_grad():
86
+ with torch.autocast(device_type='cuda', dtype=torch.bfloat16):
87
+ logits = model(inputs['input_ids'], inputs['attention_mask'])
88
+ prob = torch.sigmoid(logits).item()
89
+
90
+ print(f"AI Probability: {round(prob * 100, 2)}%")
91
+ print("Verdict:", "AI Generated" if prob > 0.5 else "Human Written")
92
+ ```
inference.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+ import torch
4
+ import torch.nn as nn
5
+ from transformers import AutoTokenizer
6
+
7
+ class SourceCodeAuthorCheck(nn.Module):
8
+ def __init__(self, vocab_size=50257, d_model=128, nhead=8, num_layers=4, dim_feedforward=512):
9
+ super().__init__()
10
+ self.embedding = nn.Embedding(vocab_size, d_model)
11
+ self.pos_encoder = nn.Parameter(torch.zeros(1, 1024, d_model))
12
+
13
+ encoder_layers = nn.TransformerEncoderLayer(
14
+ d_model=d_model, nhead=nhead, dim_feedforward=dim_feedforward, batch_first=True
15
+ )
16
+ self.transformer = nn.TransformerEncoder(encoder_layers, num_layers=num_layers)
17
+ self.fc = nn.Linear(d_model, 1)
18
+
19
+ def forward(self, input_ids, attention_mask):
20
+ seq_len = input_ids.size(1)
21
+ x = self.embedding(input_ids) + self.pos_encoder[:, :seq_len, :]
22
+
23
+ src_key_padding_mask = ~attention_mask.bool()
24
+ x = self.transformer(x, src_key_padding_mask=src_key_padding_mask)
25
+
26
+ mask_expanded = attention_mask.unsqueeze(-1).float()
27
+ sum_embeddings = torch.sum(x * mask_expanded, 1)
28
+ sum_mask = torch.clamp(mask_expanded.sum(1), min=1e-9)
29
+ pooled = sum_embeddings / sum_mask
30
+
31
+ return self.fc(pooled)
32
+
33
+ def predict(code_snippet, model, tokenizer, device):
34
+ inputs = tokenizer(
35
+ code_snippet,
36
+ return_tensors="pt",
37
+ truncation=True,
38
+ padding="max_length",
39
+ max_length=1024
40
+ ).to(device)
41
+
42
+ with torch.no_grad():
43
+ with torch.autocast(device_type='cuda', dtype=torch.bfloat16):
44
+ logits = model(inputs['input_ids'], inputs['attention_mask'])
45
+ prob = torch.sigmoid(logits).item()
46
+
47
+ return prob
48
+
49
+ def main():
50
+ if len(sys.argv) < 2:
51
+ print("Usage: python 4-inference_file.py <path_to_python_file>")
52
+ sys.exit(1)
53
+
54
+ target_file = sys.argv[1]
55
+
56
+ if not os.path.exists(target_file):
57
+ print(f"Error: File '{target_file}' not found.")
58
+ sys.exit(1)
59
+
60
+ with open(target_file, 'r', encoding='utf-8', errors='ignore') as f:
61
+ code_content = f.read()
62
+
63
+ if not code_content.strip():
64
+ print(f"Error: File '{target_file}' is empty.")
65
+ sys.exit(1)
66
+
67
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
68
+ tokenizer = AutoTokenizer.from_pretrained("gpt2")
69
+ tokenizer.pad_token = tokenizer.eos_token
70
+
71
+ model = SourceCodeAuthorCheck().to(device)
72
+ model.load_state_dict(torch.load("source_code_classifier.pth", map_location=device, weights_only=True))
73
+ model.eval()
74
+
75
+ print(f"\n--- Testing File: {target_file} ---")
76
+ prob = predict(code_content, model, tokenizer, device)
77
+ score = round(prob * 100, 2)
78
+
79
+ verdict = "AI Generated" if prob > 0.5 else "Human Written"
80
+ print(f"Verdict: {verdict} (AI Probability: {score}%)")
81
+ print(f"Preview: {code_content[:150].strip()}...\n")
82
+
83
+ if __name__ == "__main__":
84
+ main()
source_code_classifier.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1b4e8941a866804d5a583887e81b9eb7eb620530c6927ea1c83f72cecd88a679
3
+ size 29449261