Eugenios/qwen2.5-coder-1.5b-secure-codegen
Qwen2.5‑Coder‑1.5B Secure Code DoRA Adapter
Адаптер DoRA/LoRA для Qwen/Qwen2.5-Coder-1.5B-Instruct, дообученный под генерацию более безопасного кода и исправление уязвимостей. Обучение велось на парах «уязвимый код → безопасный код» на основе датасета Big‑Vul.
Model Details
- Base model:
Qwen/Qwen2.5-Coder-1.5B-Instruct - Adapter type: DoRA (Weight‑Decomposed LoRA) через PEFT
- Trainable params: ~4.46M (≈0.29% от 1.55B)
- Languages: в основном код (C/C++, Python, SQL‑фрагменты) + англ./рус. комментарии и описания
- License: следует лицензии базовой модели Qwen2.5‑Coder (см. карточку base‑модели)
- Intended format: chat‑модель с
apply_chat_template
Intended Use
Адаптер предназначен для:
- генерации более безопасных SQL‑запросов и паттернов работы с БД;
- исправления уязвимых фрагментов кода (в первую очередь C/C++ из Big‑Vul);
- объяснения причин уязвимости и предложения безопасной альтернативы.
Примеры задач:
- «Напиши функцию, выполняющую SQL‑запрос по
user_idбезопасным образом». - «Вот фрагмент с
cursor.execute(f"...")— объясни, почему он небезопасен, и перепиши безопасно». - «Дан уязвимый C/C++‑код — предложи исправленный вариант».
Out‑of‑scope
- Общий чат‑ассистент вне области кибербезопасности.
- Генерация эксплойтов, PoC‑атак и других наступательных сценариев.
- Любое использование, нарушающее лицензию/Acceptable Use базовой модели Qwen.
How to Use
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
import torch
base_model_id = "Qwen/Qwen2.5-Coder-1.5B-Instruct"
adapter_id = "<your-username>/qwen2.5-coder-1.5b-secure-codegen" # замените на ваш репозиторий
tokenizer = AutoTokenizer.from_pretrained(base_model_id, trust_remote_code=True)
base = AutoModelForCausalLM.from_pretrained(
base_model_id,
torch_dtype=torch.bfloat16 if torch.backends.mps.is_available() else torch.float32,
device_map="auto" if torch.backends.mps.is_available() else None,
trust_remote_code=True,
)
model = PeftModel.from_pretrained(base, adapter_id)
model.eval()
device = next(model.parameters()).device
prompt = "Напиши на Python функцию, которая выполняет SQL-запрос по user_id безопасным образом."
messages = [{"role": "user", "content": prompt}]
chat_text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
)
enc = tokenizer(chat_text, return_tensors="pt").to(device)
with torch.no_grad():
out = model.generate(
**enc,
max_new_tokens=256,
do_sample=False,
pad_token_id=tokenizer.eos_token_id,
)
generated = out[0, enc["input_ids"].shape[-1]:]
print(tokenizer.decode(generated, skip_special_tokens=True))Training Details
Data
- Источник:
bstee615/bigvul(Hugging Face) - Подготовка:
- берутся пары
func_src_before/func_src_after(уязвимый/исправленный код); - длина ограничена (≤4000 символов);
- формируется instruction в стиле:
{
"messages": [
{
"role": "user",
"content": "Исправь этот код, устранив уязвимость. Верни только исправленный код.\n\n<уязвимый_код>"
},
{
"role": "assistant",
"content": "<безопасный_код>"
}
]
}- Размер: 2000 пар (train+val), train/test‑split 90/10 на уровне готовых примеров.
Procedure
- Base:
Qwen/Qwen2.5-Coder-1.5B-Instruct - Adapter: DoRA через
peft.LoraConfig(use_dora=True)(если поддерживается версией PEFT) - Оптимизируемые параметры: только LoRA/DoRA‑адаптеры (base‑веса заморожены)
- Оптимизатор: AdamW (через
transformers.Trainer) - Precision:
bf16на Apple MPS (Mac),float32на CPU - Эпохи: 2
- Batch size: 2,
gradient_accumulation_steps=4(эффективный batch 8 примеров) - Learning rate: 2e‑5 с
warmup_ratio=0.05, далее линейный decay - Train runtime: ~1 час на Mac M‑серии (24 GB, MPS)
Тренинг запускался через scripts/train_qlora_secure.py из этого репозитория.
Results & Benefits
Неформальное сравнение с базовой моделью Qwen/Qwen2.5-Coder-1.5B-Instruct на ручных промптах показывает:
- SQL по `user_id` Базовая модель уже иногда использует параметризованные запросы, но ответы бывают размыты и не всегда подчёркивают безопасный шаблон. Дообученная модель стабильно генерирует код вида
cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))и даёт более фокусированное объяснение, почему это защищает от SQL‑инъекции.
- Определение небезопасного кода На промптах вида
cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")адаптер точнее указывает на SQL‑инъекцию и сразу предлагает безопасный вариант с параметрами.
- Общие свойства Адаптер не меняет архитектуру базовой модели и добавляет всего ~0.3% обучаемых параметров, поэтому:
- требования к памяти и скорость инференса почти не меняются;
- увеличивается вероятность, что модель предложит безопасный паттерн (параметризованные запросы, разделение данных и кода и т.п.) на примерах, похожих на обучающие.
Важно: адаптер не гарантирует полную безопасность генерируемого кода. Его следует использовать как помощника, а не как единственный источник истины, вместе с ручным ревью, статическим/динамическим анализом и существующими инструментами безопасности.
Limitations and Risks
- Адаптер дообучен на ограниченном числе примеров (≈2000), в основном C/C++ и SQL‑фрагменты → обобщение на другие языки и типы уязвимостей ограничено.
- Модель не гарантирует полную безопасность кода; она лишь сдвигает базовую модель в сторону более безопасных паттернов.
- Ответы могут содержать неточности, deprecated‑практики или быть неполными; их нужно перепроверять.
- Не предназначена для offensive‑security задач (поиск эксплойтов, генерация вредоносного кода).
Рекомендуется:
- использовать адаптер как помощника, а не как единственный источник истины;
- включать в пайплайн статический/динамический анализ кода и дополнительные чекеры безопасности;
- при выкладке в прод окружение проводить своё тестирование и аудит.
Acknowledgements
- Базовая модель: Qwen/Qwen2.5-Coder-1.5B-Instruct
- Датасет уязвимостей: bstee615/bigvul
Model Card Authors
- Евгений Захаров
Model Card Contact
- Hugging Face: https://huggingface.co/Eugenios
basemodel: Qwen/Qwen2.5-Coder-1.5B-Instruct libraryname: peft pipeline_tag: text-generation tags:
- base_model:adapter:Qwen/Qwen2.5-Coder-1.5B-Instruct
- lora
- transformers ---
Model Card for Model ID
<!-- Provide a quick summary of what the model is/does. -->
Model Details
Model Description
<!-- Provide a longer summary of what this model is. -->
- Developed by: [More Information Needed]
- Funded by [optional]: [More Information Needed]
- Shared by [optional]: [More Information Needed]
- Model type: [More Information Needed]
- Language(s) (NLP): [More Information Needed]
- License: [More Information Needed]
- Finetuned from model [optional]: [More Information Needed]
Model Sources [optional]
<!-- Provide the basic links for the model. -->
- Repository: [More Information Needed]
- Paper [optional]: [More Information Needed]
- Demo [optional]: [More Information Needed]
Uses
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
Direct Use
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
[More Information Needed]
Downstream Use [optional]
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
[More Information Needed]
Out-of-Scope Use
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
[More Information Needed]
Bias, Risks, and Limitations
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
[More Information Needed]
Recommendations
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
How to Get Started with the Model
Use the code below to get started with the model.
[More Information Needed]
Training Details
Training Data
<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
[More Information Needed]
Training Procedure
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
Preprocessing [optional]
[More Information Needed]
Training Hyperparameters
- Training regime: [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
Speeds, Sizes, Times [optional]
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
[More Information Needed]
Evaluation
<!-- This section describes the evaluation protocols and provides the results. -->
Testing Data, Factors & Metrics
Testing Data
<!-- This should link to a Dataset Card if possible. -->
[More Information Needed]
Factors
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
[More Information Needed]
Metrics
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
[More Information Needed]
Results
[More Information Needed]
Summary
Model Examination [optional]
<!-- Relevant interpretability work for the model goes here -->
[More Information Needed]
Environmental Impact
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
Carbon emissions can be estimated using the Machine Learning Impact calculator presented in Lacoste et al. (2019).
- Hardware Type: [More Information Needed]
- Hours used: [More Information Needed]
- Cloud Provider: [More Information Needed]
- Compute Region: [More Information Needed]
- Carbon Emitted: [More Information Needed]
Technical Specifications [optional]
Model Architecture and Objective
[More Information Needed]
Compute Infrastructure
[More Information Needed]
Hardware
[More Information Needed]
Software
[More Information Needed]
Citation [optional]
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
BibTeX:
[More Information Needed]
APA:
[More Information Needed]
Glossary [optional]
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
[More Information Needed]
More Information [optional]
[More Information Needed]
Model Card Authors [optional]
[More Information Needed]
Model Card Contact
[More Information Needed]
Framework versions
- PEFT 0.18.1
