Update README.md
Browse files
README.md
CHANGED
|
@@ -9,25 +9,65 @@ tags:
|
|
| 9 |
- code-classification
|
| 10 |
- transformer
|
| 11 |
- slm
|
|
|
|
| 12 |
---
|
| 13 |
|
| 14 |
# SourceCodeAuthorCheck-SLM-10M
|
| 15 |
|
| 16 |
[](https://huggingface.co/spaces/assix-research/SourceCodeAuthorCheck-UI)
|
| 17 |
|
| 18 |
-
A ~10 million parameter Small Language Model (SLM) Transformer designed
|
| 19 |
-
|
| 20 |
-
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.
|
| 21 |
|
| 22 |
## Live Demo
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
-
##
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
```python
|
| 33 |
import torch
|
|
@@ -35,6 +75,7 @@ import torch.nn as nn
|
|
| 35 |
from transformers import AutoTokenizer
|
| 36 |
from huggingface_hub import hf_hub_download
|
| 37 |
|
|
|
|
| 38 |
class SourceCodeAuthorCheck(nn.Module):
|
| 39 |
def __init__(self, vocab_size=50257, d_model=128, nhead=8, num_layers=4, dim_feedforward=512):
|
| 40 |
super().__init__()
|
|
@@ -60,53 +101,26 @@ class SourceCodeAuthorCheck(nn.Module):
|
|
| 60 |
pooled = sum_embeddings / sum_mask
|
| 61 |
|
| 62 |
return self.fc(pooled)
|
| 63 |
-
```
|
| 64 |
|
| 65 |
-
#
|
| 66 |
-
|
| 67 |
-
Once the class is defined, you can automatically pull the weights from Hugging Face and run inference cleanly using this helper function:
|
| 68 |
-
|
| 69 |
-
```python
|
| 70 |
-
# Initialize device and tokenizer
|
| 71 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 72 |
tokenizer = AutoTokenizer.from_pretrained("gpt2")
|
| 73 |
tokenizer.pad_token = tokenizer.eos_token
|
| 74 |
|
| 75 |
-
# Download and load model weights from the Hugging Face Hub
|
| 76 |
model = SourceCodeAuthorCheck().to(device)
|
| 77 |
model_path = hf_hub_download(repo_id="assix-research/SourceCodeAuthorCheck-SLM-10M", filename="source_code_classifier.pth")
|
| 78 |
model.load_state_dict(torch.load(model_path, map_location=device, weights_only=True))
|
| 79 |
model.eval()
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
).
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
if torch.cuda.is_available():
|
| 93 |
-
with torch.autocast(device_type='cuda', dtype=torch.bfloat16):
|
| 94 |
-
logits = model(inputs['input_ids'], inputs['attention_mask'])
|
| 95 |
-
else:
|
| 96 |
-
logits = model(inputs['input_ids'], inputs['attention_mask'])
|
| 97 |
-
|
| 98 |
-
prob = torch.sigmoid(logits).item()
|
| 99 |
-
|
| 100 |
-
verdict = "AI Generated" if prob > 0.5 else "Human Written"
|
| 101 |
-
print(f"Verdict: {verdict} (AI Probability: {prob:.1%})")
|
| 102 |
-
|
| 103 |
-
# --- Example Usage ---
|
| 104 |
-
sample_code = """
|
| 105 |
-
def calculate_factorial(n):
|
| 106 |
-
if n == 0:
|
| 107 |
-
return 1
|
| 108 |
-
return n * calculate_factorial(n-1)
|
| 109 |
-
"""
|
| 110 |
-
|
| 111 |
-
predict_source(sample_code)
|
| 112 |
```
|
|
|
|
| 9 |
- code-classification
|
| 10 |
- transformer
|
| 11 |
- slm
|
| 12 |
+
- binary-classification
|
| 13 |
---
|
| 14 |
|
| 15 |
# SourceCodeAuthorCheck-SLM-10M
|
| 16 |
|
| 17 |
[](https://huggingface.co/spaces/assix-research/SourceCodeAuthorCheck-UI)
|
| 18 |
|
| 19 |
+
A ~10 million parameter Small Language Model (SLM) Transformer designed to detect whether a Python source code file was written by a human or generated by an AI model.
|
|
|
|
|
|
|
| 20 |
|
| 21 |
## Live Demo
|
| 22 |
+
Test the model directly in your browser without writing code: **[SourceCodeAuthorCheck Web UI](https://huggingface.co/spaces/assix-research/SourceCodeAuthorCheck-UI)**
|
| 23 |
+
|
| 24 |
+
---
|
| 25 |
+
|
| 26 |
+
## 🔬 Training Pipeline & Techniques
|
| 27 |
+
|
| 28 |
+
This model was built from scratch using a custom PyTorch TransformerEncoder architecture (~9.6M parameters). The training pipeline utilized several specific techniques to ensure accurate binary classification and optimal hardware utilization.
|
| 29 |
+
|
| 30 |
+
### 1. Temporal Data Separation
|
| 31 |
+
To create a stark contrast between human and AI coding paradigms, the dataset relies on temporal splitting:
|
| 32 |
+
* **Human Baseline (Class 0):** Python source code extracted from GitHub repositories created in **Q3 2017 and prior**, guaranteeing the code predates modern generative AI.
|
| 33 |
+
* **GenAI Baseline (Class 1):** Synthetic datasets structured to mimic the exact architectural paradigms, repetitive docstrings, and token distributions typical of models operating in **Q3 2026**.
|
| 34 |
|
| 35 |
+
### 2. Hardware Optimization (NVIDIA DGX Spark)
|
| 36 |
+
The model was trained natively on an **NVIDIA DGX Spark (Grace Blackwell architecture)**.
|
| 37 |
+
* **Automatic Mixed Precision (AMP):** We utilized PyTorch's `torch.autocast` targeting `bfloat16`. This leverages Blackwell's 5th-generation Tensor Cores, accelerating matrix multiplications while maintaining numerical stability during backpropagation.
|
| 38 |
+
* **Gradient Scaling:** Paired with AMP, `torch.amp.GradScaler` was used to prevent underflow errors during the transition between FP32 and BF16 formats.
|
| 39 |
|
| 40 |
+
### 3. Optimization & Loss
|
| 41 |
+
* **Loss Function:** `BCEWithLogitsLoss`. This combines a Sigmoid layer and Binary Cross Entropy Loss in a single class, providing better numerical stability than applying Sigmoid followed by standard BCELoss.
|
| 42 |
+
* **Optimizer:** `AdamW` (Adam with Weight Decay) to enhance generalization and prevent overfitting on the synthetic AI subsets.
|
| 43 |
|
| 44 |
+
---
|
| 45 |
+
|
| 46 |
+
## 💻 Usage: The Inference Script
|
| 47 |
+
|
| 48 |
+
The easiest way to use this model locally is via the standalone `inference.py` script included in this repository. It includes the required architecture class and handles downloading the weights automatically.
|
| 49 |
|
| 50 |
+
**1. Download the script**
|
| 51 |
+
You can download the script directly from the files tab: [inference.py](https://huggingface.co/assix-research/SourceCodeAuthorCheck-SLM-10M/blob/main/inference.py)
|
| 52 |
+
|
| 53 |
+
**2. Run against any Python file**
|
| 54 |
+
Pass the path of the file you want to analyze directly to the script:
|
| 55 |
+
```bash
|
| 56 |
+
python inference.py my_script.py
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
**Example Output:**
|
| 60 |
+
```text
|
| 61 |
+
--- Testing File: my_script.py ---
|
| 62 |
+
Verdict: Human Written (AI Probability: 37.89%)
|
| 63 |
+
Preview: def process_data(items):...
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
---
|
| 67 |
+
|
| 68 |
+
## 🛠 Programmatic Usage
|
| 69 |
+
|
| 70 |
+
If you want to integrate the model directly into your own Python applications, you must define the architecture class before loading the weights.
|
| 71 |
|
| 72 |
```python
|
| 73 |
import torch
|
|
|
|
| 75 |
from transformers import AutoTokenizer
|
| 76 |
from huggingface_hub import hf_hub_download
|
| 77 |
|
| 78 |
+
# 1. Define the Architecture
|
| 79 |
class SourceCodeAuthorCheck(nn.Module):
|
| 80 |
def __init__(self, vocab_size=50257, d_model=128, nhead=8, num_layers=4, dim_feedforward=512):
|
| 81 |
super().__init__()
|
|
|
|
| 101 |
pooled = sum_embeddings / sum_mask
|
| 102 |
|
| 103 |
return self.fc(pooled)
|
|
|
|
| 104 |
|
| 105 |
+
# 2. Load Tokenizer and Model Weights
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 107 |
tokenizer = AutoTokenizer.from_pretrained("gpt2")
|
| 108 |
tokenizer.pad_token = tokenizer.eos_token
|
| 109 |
|
|
|
|
| 110 |
model = SourceCodeAuthorCheck().to(device)
|
| 111 |
model_path = hf_hub_download(repo_id="assix-research/SourceCodeAuthorCheck-SLM-10M", filename="source_code_classifier.pth")
|
| 112 |
model.load_state_dict(torch.load(model_path, map_location=device, weights_only=True))
|
| 113 |
model.eval()
|
| 114 |
|
| 115 |
+
# 3. Analyze Code Snippet
|
| 116 |
+
code_snippet = "print('Hello World')"
|
| 117 |
+
inputs = tokenizer(
|
| 118 |
+
code_snippet, return_tensors="pt", truncation=True, padding="max_length", max_length=1024
|
| 119 |
+
).to(device)
|
| 120 |
+
|
| 121 |
+
with torch.no_grad():
|
| 122 |
+
logits = model(inputs['input_ids'], inputs['attention_mask'])
|
| 123 |
+
prob = torch.sigmoid(logits).item()
|
| 124 |
+
|
| 125 |
+
print(f"AI Probability: {prob:.1%}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
```
|