HusainHG commited on
Commit
dd120eb
Β·
verified Β·
1 Parent(s): 652dd27

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +197 -197
app.py CHANGED
@@ -1,197 +1,197 @@
1
- from flask import Flask, request, jsonify, send_from_directory
2
- from flask_cors import CORS
3
- from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
4
- import torch
5
- import os
6
- import sys
7
-
8
- app = Flask(__name__, static_folder='static')
9
- CORS(app)
10
-
11
- MODEL_NAME = "KASHH-4/mistral_fine-tuned_new"
12
-
13
- print("\n" + "="*80)
14
- print("πŸš€ LEGALDOCS AI - MODEL INITIALIZATION")
15
- print("="*80)
16
- print(f"πŸ“¦ Model: {MODEL_NAME}")
17
- print(f"🐍 Python: {torch.__version__}")
18
- print(f"πŸ”₯ PyTorch: {torch.__version__}")
19
- print(f"πŸ€— Transformers: Loading...")
20
- print("="*80 + "\n")
21
-
22
- print("Loading tokenizer from YOUR merged model (slow tokenizer)...")
23
- tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, use_fast=False)
24
-
25
- if tokenizer.pad_token is None:
26
- tokenizer.pad_token = tokenizer.eos_token
27
-
28
- print("βœ… Tokenizer loaded successfully!")
29
- print(f" - Vocab size: {tokenizer.vocab_size}")
30
- print(f" - Model max length: {tokenizer.model_max_length}")
31
- print(f" - Pad token: {tokenizer.pad_token}")
32
-
33
- print("Loading YOUR model weights...")
34
- # Optimized for 18GB RAM (Hugging Face Spaces) - use 4-bit quantization for speed
35
- # This will use ~10-12GB RAM and be MUCH faster than 8-bit
36
- quantization_config = BitsAndBytesConfig(
37
- load_in_4bit=True, # 4-bit is faster and uses less RAM than 8-bit
38
- bnb_4bit_compute_dtype=torch.float16, # Use FP16 for computations (faster)
39
- bnb_4bit_quant_type="nf4", # NormalFloat4 - better quality than standard 4-bit
40
- bnb_4bit_use_double_quant=True, # Double quantization for better performance
41
- )
42
-
43
- model = AutoModelForCausalLM.from_pretrained(
44
- MODEL_NAME,
45
- quantization_config=quantization_config,
46
- device_map="auto",
47
- low_cpu_mem_usage=True,
48
- trust_remote_code=True,
49
- torch_dtype=torch.float16, # Use FP16 for faster inference
50
- )
51
-
52
- print("βœ… Model loaded successfully!")
53
- print(f" - Device: {model.device}")
54
- print(f" - Model type: {type(model).__name__}")
55
- print(f" - Quantization: 4-bit NF4")
56
- print(f" - Compute dtype: float16")
57
-
58
- # Memory info
59
- if torch.cuda.is_available():
60
- print(f" - GPU: {torch.cuda.get_device_name(0)}")
61
- print(f" - GPU Memory allocated: {torch.cuda.memory_allocated(0) / 1024**3:.2f} GB")
62
- print(f" - GPU Memory reserved: {torch.cuda.memory_reserved(0) / 1024**3:.2f} GB")
63
- else:
64
- print(f" - Running on CPU")
65
-
66
- print("\n" + "="*80)
67
- print("βœ… MODEL READY - Server starting...")
68
- print("="*80 + "\n")
69
-
70
-
71
- @app.route('/')
72
- def index():
73
- return send_from_directory('static', 'index.html')
74
-
75
-
76
- @app.route('/api/generate', methods=['POST'])
77
- def generate():
78
- import time
79
- try:
80
- print("\n" + "="*80, flush=True)
81
- print("πŸš€ NEW GENERATION REQUEST RECEIVED", flush=True)
82
- print("="*80, flush=True)
83
- sys.stdout.flush()
84
-
85
- data = request.json
86
-
87
- if not data or 'prompt' not in data:
88
- print("❌ ERROR: Missing prompt in request body", flush=True)
89
- sys.stdout.flush()
90
- return jsonify({'error': 'Missing prompt in request body'}), 400
91
-
92
- prompt = data['prompt']
93
- max_new_tokens = data.get('max_new_tokens', 256)
94
- temperature = data.get('temperature', 0.7)
95
- top_p = data.get('top_p', 0.9)
96
-
97
- print(f"\nπŸ“ REQUEST PARAMETERS:", flush=True)
98
- print(f" - Prompt length: {len(prompt)} characters", flush=True)
99
- print(f" - Prompt preview: {prompt[:200]}...", flush=True)
100
- print(f" - Max new tokens: {max_new_tokens}", flush=True)
101
- print(f" - Temperature: {temperature}", flush=True)
102
- print(f" - Top P: {top_p}", flush=True)
103
- sys.stdout.flush()
104
-
105
- print(f"\nπŸ”„ TOKENIZING INPUT...", flush=True)
106
- sys.stdout.flush()
107
- tokenize_start = time.time()
108
- inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
109
- tokenize_time = time.time() - tokenize_start
110
- input_token_count = inputs['input_ids'].shape[1]
111
- print(f" βœ… Tokenization complete in {tokenize_time:.2f}s", flush=True)
112
- print(f" - Input tokens: {input_token_count}", flush=True)
113
- print(f" - Device: {model.device}", flush=True)
114
- sys.stdout.flush()
115
-
116
- print(f"\n🧠 GENERATING TEXT WITH MODEL...", flush=True)
117
- print(f" Model: {MODEL_NAME}", flush=True)
118
- print(f" Status: Running inference...", flush=True)
119
- sys.stdout.flush()
120
- generation_start = time.time()
121
-
122
- with torch.no_grad():
123
- outputs = model.generate(
124
- **inputs,
125
- max_new_tokens=max_new_tokens,
126
- temperature=temperature,
127
- top_p=top_p,
128
- do_sample=True,
129
- pad_token_id=tokenizer.eos_token_id
130
- )
131
-
132
- generation_time = time.time() - generation_start
133
- output_token_count = outputs.shape[1]
134
- tokens_generated = output_token_count - input_token_count
135
- tokens_per_second = tokens_generated / generation_time if generation_time > 0 else 0
136
-
137
- print(f" βœ… Generation complete in {generation_time:.2f}s", flush=True)
138
- print(f" - Output tokens: {output_token_count}", flush=True)
139
- print(f" - New tokens generated: {tokens_generated}", flush=True)
140
- print(f" - Speed: {tokens_per_second:.2f} tokens/second", flush=True)
141
- sys.stdout.flush()
142
-
143
- print(f"\nπŸ”„ DECODING OUTPUT...", flush=True)
144
- sys.stdout.flush()
145
- decode_start = time.time()
146
- # Decode the full output
147
- full_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
148
- decode_time = time.time() - decode_start
149
- print(f" βœ… Decoding complete in {decode_time:.2f}s", flush=True)
150
- sys.stdout.flush()
151
-
152
- # Remove the prompt from the output to return only the generated text
153
- generated_text = full_output[len(prompt):].strip()
154
-
155
- print(f"\nπŸ“Š FINAL RESULTS:", flush=True)
156
- print(f" - Generated text length: {len(generated_text)} characters", flush=True)
157
- print(f" - Generated text preview: {generated_text[:200]}...", flush=True)
158
- print(f" - Total processing time: {(time.time() - tokenize_start):.2f}s", flush=True)
159
- sys.stdout.flush()
160
-
161
- print(f"\nβœ… REQUEST COMPLETED SUCCESSFULLY", flush=True)
162
- print("="*80 + "\n", flush=True)
163
- sys.stdout.flush()
164
-
165
- return jsonify({
166
- 'generated_text': generated_text,
167
- 'prompt': prompt
168
- })
169
-
170
- except Exception as e:
171
- print(f"\n❌ ERROR DURING GENERATION:", flush=True)
172
- print(f" Error type: {type(e).__name__}", flush=True)
173
- print(f" Error message: {str(e)}", flush=True)
174
- sys.stdout.flush()
175
- import traceback
176
- print(f" Traceback:\n{traceback.format_exc()}", flush=True)
177
- print("="*80 + "\n", flush=True)
178
- sys.stdout.flush()
179
- return jsonify({'error': str(e)}), 500
180
-
181
-
182
- @app.route('/api/health', methods=['GET'])
183
- def health():
184
- return jsonify({
185
- 'status': 'ok',
186
- 'model': MODEL_NAME,
187
- 'device': str(model.device)
188
- })
189
-
190
-
191
- if __name__ == '__main__':
192
- port = int(os.environ.get('PORT', 7860))
193
- print(f"\n🌐 Starting Flask server on port {port}...")
194
- print(f"πŸ”— Access the app at: http://localhost:{port}")
195
- print(f"πŸ“Š Health check: http://localhost:{port}/api/health")
196
- print(f"πŸš€ API endpoint: http://localhost:{port}/api/generate\n")
197
- app.run(host='0.0.0.0', port=port, debug=False)
 
1
+ from flask import Flask, request, jsonify, send_from_directory
2
+ from flask_cors import CORS
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
4
+ import torch
5
+ import os
6
+ import sys
7
+
8
+ app = Flask(__name__, static_folder='static')
9
+ CORS(app)
10
+
11
+ MODEL_NAME = "KASHH-4/Gemma-finetuned"
12
+
13
+ print("\n" + "="*80)
14
+ print("πŸš€ LEGALDOCS AI - MODEL INITIALIZATION")
15
+ print("="*80)
16
+ print(f"πŸ“¦ Model: {MODEL_NAME}")
17
+ print(f"🐍 Python: {torch.__version__}")
18
+ print(f"πŸ”₯ PyTorch: {torch.__version__}")
19
+ print(f"πŸ€— Transformers: Loading...")
20
+ print("="*80 + "\n")
21
+
22
+ print("Loading tokenizer from YOUR merged model (slow tokenizer)...")
23
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, use_fast=False)
24
+
25
+ if tokenizer.pad_token is None:
26
+ tokenizer.pad_token = tokenizer.eos_token
27
+
28
+ print("βœ… Tokenizer loaded successfully!")
29
+ print(f" - Vocab size: {tokenizer.vocab_size}")
30
+ print(f" - Model max length: {tokenizer.model_max_length}")
31
+ print(f" - Pad token: {tokenizer.pad_token}")
32
+
33
+ print("Loading YOUR model weights...")
34
+ # Optimized for 18GB RAM (Hugging Face Spaces) - use 4-bit quantization for speed
35
+ # This will use ~10-12GB RAM and be MUCH faster than 8-bit
36
+ quantization_config = BitsAndBytesConfig(
37
+ load_in_4bit=True, # 4-bit is faster and uses less RAM than 8-bit
38
+ bnb_4bit_compute_dtype=torch.float16, # Use FP16 for computations (faster)
39
+ bnb_4bit_quant_type="nf4", # NormalFloat4 - better quality than standard 4-bit
40
+ bnb_4bit_use_double_quant=True, # Double quantization for better performance
41
+ )
42
+
43
+ model = AutoModelForCausalLM.from_pretrained(
44
+ MODEL_NAME,
45
+ quantization_config=quantization_config,
46
+ device_map="auto",
47
+ low_cpu_mem_usage=True,
48
+ trust_remote_code=True,
49
+ torch_dtype=torch.float16, # Use FP16 for faster inference
50
+ )
51
+
52
+ print("βœ… Model loaded successfully!")
53
+ print(f" - Device: {model.device}")
54
+ print(f" - Model type: {type(model).__name__}")
55
+ print(f" - Quantization: 4-bit NF4")
56
+ print(f" - Compute dtype: float16")
57
+
58
+ # Memory info
59
+ if torch.cuda.is_available():
60
+ print(f" - GPU: {torch.cuda.get_device_name(0)}")
61
+ print(f" - GPU Memory allocated: {torch.cuda.memory_allocated(0) / 1024**3:.2f} GB")
62
+ print(f" - GPU Memory reserved: {torch.cuda.memory_reserved(0) / 1024**3:.2f} GB")
63
+ else:
64
+ print(f" - Running on CPU")
65
+
66
+ print("\n" + "="*80)
67
+ print("βœ… MODEL READY - Server starting...")
68
+ print("="*80 + "\n")
69
+
70
+
71
+ @app.route('/')
72
+ def index():
73
+ return send_from_directory('static', 'index.html')
74
+
75
+
76
+ @app.route('/api/generate', methods=['POST'])
77
+ def generate():
78
+ import time
79
+ try:
80
+ print("\n" + "="*80, flush=True)
81
+ print("πŸš€ NEW GENERATION REQUEST RECEIVED", flush=True)
82
+ print("="*80, flush=True)
83
+ sys.stdout.flush()
84
+
85
+ data = request.json
86
+
87
+ if not data or 'prompt' not in data:
88
+ print("❌ ERROR: Missing prompt in request body", flush=True)
89
+ sys.stdout.flush()
90
+ return jsonify({'error': 'Missing prompt in request body'}), 400
91
+
92
+ prompt = data['prompt']
93
+ max_new_tokens = data.get('max_new_tokens', 256)
94
+ temperature = data.get('temperature', 0.7)
95
+ top_p = data.get('top_p', 0.9)
96
+
97
+ print(f"\nπŸ“ REQUEST PARAMETERS:", flush=True)
98
+ print(f" - Prompt length: {len(prompt)} characters", flush=True)
99
+ print(f" - Prompt preview: {prompt[:200]}...", flush=True)
100
+ print(f" - Max new tokens: {max_new_tokens}", flush=True)
101
+ print(f" - Temperature: {temperature}", flush=True)
102
+ print(f" - Top P: {top_p}", flush=True)
103
+ sys.stdout.flush()
104
+
105
+ print(f"\nπŸ”„ TOKENIZING INPUT...", flush=True)
106
+ sys.stdout.flush()
107
+ tokenize_start = time.time()
108
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
109
+ tokenize_time = time.time() - tokenize_start
110
+ input_token_count = inputs['input_ids'].shape[1]
111
+ print(f" βœ… Tokenization complete in {tokenize_time:.2f}s", flush=True)
112
+ print(f" - Input tokens: {input_token_count}", flush=True)
113
+ print(f" - Device: {model.device}", flush=True)
114
+ sys.stdout.flush()
115
+
116
+ print(f"\n🧠 GENERATING TEXT WITH MODEL...", flush=True)
117
+ print(f" Model: {MODEL_NAME}", flush=True)
118
+ print(f" Status: Running inference...", flush=True)
119
+ sys.stdout.flush()
120
+ generation_start = time.time()
121
+
122
+ with torch.no_grad():
123
+ outputs = model.generate(
124
+ **inputs,
125
+ max_new_tokens=max_new_tokens,
126
+ temperature=temperature,
127
+ top_p=top_p,
128
+ do_sample=True,
129
+ pad_token_id=tokenizer.eos_token_id
130
+ )
131
+
132
+ generation_time = time.time() - generation_start
133
+ output_token_count = outputs.shape[1]
134
+ tokens_generated = output_token_count - input_token_count
135
+ tokens_per_second = tokens_generated / generation_time if generation_time > 0 else 0
136
+
137
+ print(f" βœ… Generation complete in {generation_time:.2f}s", flush=True)
138
+ print(f" - Output tokens: {output_token_count}", flush=True)
139
+ print(f" - New tokens generated: {tokens_generated}", flush=True)
140
+ print(f" - Speed: {tokens_per_second:.2f} tokens/second", flush=True)
141
+ sys.stdout.flush()
142
+
143
+ print(f"\nπŸ”„ DECODING OUTPUT...", flush=True)
144
+ sys.stdout.flush()
145
+ decode_start = time.time()
146
+ # Decode the full output
147
+ full_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
148
+ decode_time = time.time() - decode_start
149
+ print(f" βœ… Decoding complete in {decode_time:.2f}s", flush=True)
150
+ sys.stdout.flush()
151
+
152
+ # Remove the prompt from the output to return only the generated text
153
+ generated_text = full_output[len(prompt):].strip()
154
+
155
+ print(f"\nπŸ“Š FINAL RESULTS:", flush=True)
156
+ print(f" - Generated text length: {len(generated_text)} characters", flush=True)
157
+ print(f" - Generated text preview: {generated_text[:200]}...", flush=True)
158
+ print(f" - Total processing time: {(time.time() - tokenize_start):.2f}s", flush=True)
159
+ sys.stdout.flush()
160
+
161
+ print(f"\nβœ… REQUEST COMPLETED SUCCESSFULLY", flush=True)
162
+ print("="*80 + "\n", flush=True)
163
+ sys.stdout.flush()
164
+
165
+ return jsonify({
166
+ 'generated_text': generated_text,
167
+ 'prompt': prompt
168
+ })
169
+
170
+ except Exception as e:
171
+ print(f"\n❌ ERROR DURING GENERATION:", flush=True)
172
+ print(f" Error type: {type(e).__name__}", flush=True)
173
+ print(f" Error message: {str(e)}", flush=True)
174
+ sys.stdout.flush()
175
+ import traceback
176
+ print(f" Traceback:\n{traceback.format_exc()}", flush=True)
177
+ print("="*80 + "\n", flush=True)
178
+ sys.stdout.flush()
179
+ return jsonify({'error': str(e)}), 500
180
+
181
+
182
+ @app.route('/api/health', methods=['GET'])
183
+ def health():
184
+ return jsonify({
185
+ 'status': 'ok',
186
+ 'model': MODEL_NAME,
187
+ 'device': str(model.device)
188
+ })
189
+
190
+
191
+ if __name__ == '__main__':
192
+ port = int(os.environ.get('PORT', 7860))
193
+ print(f"\n🌐 Starting Flask server on port {port}...")
194
+ print(f"πŸ”— Access the app at: http://localhost:{port}")
195
+ print(f"πŸ“Š Health check: http://localhost:{port}/api/health")
196
+ print(f"πŸš€ API endpoint: http://localhost:{port}/api/generate\n")
197
+ app.run(host='0.0.0.0', port=port, debug=False)