Vilyam888 commited on
Commit
5668ca7
·
verified ·
1 Parent(s): 449de1e

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. README.md +123 -0
  2. inference.py +71 -0
README.md ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ license: apache-2.0
4
+ base_model: Qwen/Qwen2.5-Coder-3B-Instruct
5
+ pipeline_tag: text-generation
6
+ tags:
7
+ - code
8
+ - code-analysis
9
+ - qwen
10
+ - qwen2
11
+ - text-generation
12
+ - transformers
13
+ - fine-tuned
14
+ ---
15
+
16
+ # Code Analyzer Model
17
+
18
+ Fine-tuned версия модели Qwen2.5-Coder-3B-Instruct для анализа кода и ответов на вопросы о программировании.
19
+
20
+ ## Описание модели
21
+
22
+ Эта модель была обучена на датасете ITOG для анализа кода и предоставления ответов на вопросы, связанные с программированием. Модель основана на Qwen2.5-Coder-3B-Instruct и дообучена с использованием LoRA (Low-Rank Adaptation).
23
+
24
+ ## Быстрый старт
25
+
26
+ Вы можете использовать эту модель прямо в интерфейсе Hugging Face с помощью кнопки "Use this model" или загрузить локально.
27
+
28
+ ## Использование
29
+
30
+ ### С помощью transformers
31
+
32
+ ```python
33
+ from transformers import AutoModelForCausalLM, AutoTokenizer
34
+ import torch
35
+
36
+ model_name = "Vilyam888/Code_analyze.1.0"
37
+
38
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
39
+ model = AutoModelForCausalLM.from_pretrained(
40
+ model_name,
41
+ torch_dtype=torch.bfloat16,
42
+ device_map="auto",
43
+ trust_remote_code=True
44
+ )
45
+
46
+ # Формат запроса
47
+ prompt = "Проанализируй этот код:\ndef hello():\n print('Hello, World!')"
48
+
49
+ # Форматирование в стиле обучения
50
+ text = f"{prompt}\n\nОтвет:\n"
51
+
52
+ inputs = tokenizer(text, return_tensors="pt").to(model.device)
53
+
54
+ with torch.no_grad():
55
+ outputs = model.generate(
56
+ **inputs,
57
+ max_new_tokens=512,
58
+ temperature=0.7,
59
+ top_p=0.8,
60
+ top_k=20,
61
+ repetition_penalty=1.05,
62
+ do_sample=True
63
+ )
64
+
65
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
66
+ print(response)
67
+ ```
68
+
69
+ ### С помощью pipeline
70
+
71
+ ```python
72
+ from transformers import pipeline
73
+
74
+ model_name = "Vilyam888/Code_analyze.1.0"
75
+
76
+ generator = pipeline(
77
+ "text-generation",
78
+ model=model_name,
79
+ tokenizer=model_name,
80
+ trust_remote_code=True,
81
+ device_map="auto"
82
+ )
83
+
84
+ prompt = "Объясни, что делает этот код:\ndef factorial(n):\n if n <= 1:\n return 1\n return n * factorial(n-1)"
85
+ text = f"{prompt}\n\nОтвет:\n"
86
+
87
+ result = generator(
88
+ text,
89
+ max_new_tokens=512,
90
+ temperature=0.7,
91
+ top_p=0.8,
92
+ top_k=20,
93
+ repetition_penalty=1.05,
94
+ do_sample=True
95
+ )
96
+
97
+ print(result[0]["generated_text"])
98
+ ```
99
+
100
+ ## Детали обучения
101
+
102
+ - **Базовая модель:** Qwen/Qwen2.5-Coder-3B-Instruct
103
+ - **Метод обучения:** LoRA (Low-Rank Adaptation)
104
+ - **Параметры LoRA:**
105
+ - `r`: 16
106
+ - `lora_alpha`: 32
107
+ - `lora_dropout`: 0.05
108
+ - **Фреймворк:** TRL (Transformer Reinforcement Learning)
109
+ - **Формат данных:** JSONL с полями `input` и `output`
110
+
111
+ ## Ограничения
112
+
113
+ - Модель обучена на русском языке для анализа кода
114
+ - Может генерировать неточные или неполные ответы
115
+ - Требует GPU для эффективной работы
116
+
117
+ ## Лицензия
118
+
119
+ Apache 2.0
120
+
121
+ ## Авторы
122
+
123
+ Fine-tuned by Vilyam888
inference.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Inference code for Code Analyzer Model
3
+ This file enables the "Use this model" button on Hugging Face.
4
+ """
5
+
6
+ from transformers import AutoModelForCausalLM, AutoTokenizer
7
+ import torch
8
+
9
+
10
+ def load_model_and_tokenizer(model_name: str):
11
+ """Load model and tokenizer"""
12
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
13
+ model = AutoModelForCausalLM.from_pretrained(
14
+ model_name,
15
+ torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
16
+ device_map="auto",
17
+ trust_remote_code=True
18
+ )
19
+ return model, tokenizer
20
+
21
+
22
+ def generate_response(
23
+ model,
24
+ tokenizer,
25
+ prompt: str,
26
+ max_new_tokens: int = 512,
27
+ temperature: float = 0.7,
28
+ top_p: float = 0.8,
29
+ top_k: int = 20,
30
+ repetition_penalty: float = 1.05,
31
+ ):
32
+ """Generate response for a given prompt"""
33
+ # Format prompt in training style
34
+ text = f"{prompt}\n\nОтвет:\n"
35
+
36
+ inputs = tokenizer(text, return_tensors="pt").to(model.device)
37
+
38
+ with torch.no_grad():
39
+ outputs = model.generate(
40
+ **inputs,
41
+ max_new_tokens=max_new_tokens,
42
+ temperature=temperature,
43
+ top_p=top_p,
44
+ top_k=top_k,
45
+ repetition_penalty=repetition_penalty,
46
+ do_sample=True,
47
+ pad_token_id=tokenizer.eos_token_id
48
+ )
49
+
50
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
51
+ # Extract only the answer part
52
+ if "Ответ:" in response:
53
+ response = response.split("Ответ:")[-1].strip()
54
+
55
+ return response
56
+
57
+
58
+ if __name__ == "__main__":
59
+ # Example usage
60
+ model_name = "Vilyam888/Code_analyze.1.0"
61
+
62
+ print("Loading model...")
63
+ model, tokenizer = load_model_and_tokenizer(model_name)
64
+
65
+ prompt = "Проанализируй этот код:\ndef hello():\n print('Hello, World!')"
66
+
67
+ print(f"\nPrompt: {prompt}\n")
68
+ print("Generating response...")
69
+
70
+ response = generate_response(model, tokenizer, prompt)
71
+ print(f"\nResponse: {response}")