VietCat commited on
Commit
d78035c
·
1 Parent(s): a539a2e

adjust generation time

Browse files
Files changed (1) hide show
  1. app.py +23 -16
app.py CHANGED
@@ -11,8 +11,9 @@ import psutil
11
 
12
  # Print system resources for debugging
13
  def print_system_resources():
14
- cpu_percent = psutil.cpu_percent(interval=1)
15
  memory = psutil.virtual_memory()
 
 
16
  print(f"CPU usage: {cpu_percent}%")
17
  print(f"Memory usage: {memory.percent}% ({memory.used/1e9:.2f}/{memory.total/1e9:.2f} GB)")
18
 
@@ -35,6 +36,11 @@ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
35
  model.to(device)
36
  model.eval()
37
 
 
 
 
 
 
38
  # Print device and memory info for debugging
39
  print(f"Device: {device}")
40
  print(f"Memory allocated: {torch.cuda.memory_allocated(device)/1e9:.2f} GB" if torch.cuda.is_available() else "CPU only")
@@ -42,14 +48,14 @@ print_system_resources()
42
 
43
  def clean_text(text):
44
  """Clean generated text by removing non-alphabetic characters and extra spaces."""
45
- text = re.sub(r'[^\w\s.,!?]', '', text) # Remove non-alphabetic characters
46
- text = re.sub(r'\s+', ' ', text).strip() # Normalize spaces
47
  return text
48
 
49
- def generate_text(prompt, max_length=50):
50
  try:
51
  start_time = time.time()
52
- print_system_resources() # Print resources before generation
53
  # Encode input with attention mask
54
  inputs = tokenizer(
55
  prompt,
@@ -63,19 +69,19 @@ def generate_text(prompt, max_length=50):
63
  outputs = model.generate(
64
  input_ids=inputs["input_ids"],
65
  attention_mask=inputs["attention_mask"],
66
- max_new_tokens=20, # Reduce to speed up
67
- min_length=10, # Ensure minimum output length
68
- do_sample=False, # Use greedy decoding for consistency
69
- num_beams=1, # Disable beam search for speed
 
70
  no_repeat_ngram_size=2,
71
- pad_token_id=tokenizer.pad_token_id,
72
- early_stopping=True
73
  )
74
  generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
75
- print(f"Raw output: {generated_text}") # Debug raw output
76
  cleaned_text = clean_text(generated_text)
77
  elapsed_time = time.time() - start_time
78
- print_system_resources() # Print resources after generation
79
  print(f"Generation time: {elapsed_time:.2f} seconds")
80
  return cleaned_text
81
  except Exception as e:
@@ -88,9 +94,10 @@ demo = gr.Interface(
88
  gr.Textbox(
89
  label="Nhập văn bản đầu vào",
90
  placeholder="Viết gì đó bằng tiếng Việt...",
91
- value="Hôm nay là một ngày đẹp trời" # Set default text
92
  ),
93
- gr.Slider(20, 100, value=50, step=10, label="Độ dài tối đa")
 
94
  ],
95
  outputs="text",
96
  title="Sinh văn bản tiếng Việt",
@@ -99,4 +106,4 @@ demo = gr.Interface(
99
  )
100
 
101
  if __name__ == "__main__":
102
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
11
 
12
  # Print system resources for debugging
13
  def print_system_resources():
 
14
  memory = psutil.virtual_memory()
15
+ cpu_percent = psutil.cpu_percent(interval=1)
16
+ print(f"Total physical memory: {memory.total/1e9:.2f} GB")
17
  print(f"CPU usage: {cpu_percent}%")
18
  print(f"Memory usage: {memory.percent}% ({memory.used/1e9:.2f}/{memory.total/1e9:.2f} GB)")
19
 
 
36
  model.to(device)
37
  model.eval()
38
 
39
+ # Apply quantization to reduce memory and speed up
40
+ model = torch.quantization.quantize_dynamic(
41
+ model, {torch.nn.Linear}, dtype=torch.qint8
42
+ )
43
+
44
  # Print device and memory info for debugging
45
  print(f"Device: {device}")
46
  print(f"Memory allocated: {torch.cuda.memory_allocated(device)/1e9:.2f} GB" if torch.cuda.is_available() else "CPU only")
 
48
 
49
  def clean_text(text):
50
  """Clean generated text by removing non-alphabetic characters and extra spaces."""
51
+ text = re.sub(r'[^\w\s.,!?àáâãèéêìíòóôõùúýăđĩũơưạảấầẩẫậắằẳẵặẹẻẽếềểễệỉịọỏốồổỗộớờởỡợụủứừửữựỳỵỷỹ]', '', text)
52
+ text = re.sub(r'\s+', ' ', text).strip()
53
  return text
54
 
55
+ def generate_text(prompt, max_length=50, temperature=0.9):
56
  try:
57
  start_time = time.time()
58
+ print_system_resources()
59
  # Encode input with attention mask
60
  inputs = tokenizer(
61
  prompt,
 
69
  outputs = model.generate(
70
  input_ids=inputs["input_ids"],
71
  attention_mask=inputs["attention_mask"],
72
+ max_new_tokens=25, # Slightly increase for more content
73
+ min_length=10,
74
+ do_sample=True, # Enable sampling for diversity
75
+ top_k=50, # Limit to top 50 tokens
76
+ top_p=0.9, # Nucleus sampling
77
  no_repeat_ngram_size=2,
78
+ pad_token_id=tokenizer.pad_token_id
 
79
  )
80
  generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
81
+ print(f"Raw output: {generated_text}")
82
  cleaned_text = clean_text(generated_text)
83
  elapsed_time = time.time() - start_time
84
+ print_system_resources()
85
  print(f"Generation time: {elapsed_time:.2f} seconds")
86
  return cleaned_text
87
  except Exception as e:
 
94
  gr.Textbox(
95
  label="Nhập văn bản đầu vào",
96
  placeholder="Viết gì đó bằng tiếng Việt...",
97
+ value="Hôm nay là một ngày đẹp trời" # Default text
98
  ),
99
+ gr.Slider(20, 100, value=50, step=10, label="Độ dài tối đa"),
100
+ gr.Slider(0.7, 1.0, value=0.9, step=0.1, label="Nhiệt độ (Temperature)")
101
  ],
102
  outputs="text",
103
  title="Sinh văn bản tiếng Việt",
 
106
  )
107
 
108
  if __name__ == "__main__":
109
+ demo.launch(server_name="0.0.0.0", server_port=7860, queue=False)