Aananda-Giri commited on
Commit
cdb697b
·
1 Parent(s): 0027d0f

Update space

Browse files
Files changed (4) hide show
  1. README.md +16 -1
  2. app.py +75 -57
  3. app_autogenerated_code.py +64 -0
  4. app_by_claude.py +54 -0
README.md CHANGED
@@ -10,4 +10,19 @@ pinned: false
10
  short_description: chat with gpt2-nepali
11
  ---
12
 
13
- An example chatbot using [Gradio](https://gradio.app), [`huggingface_hub`](https://huggingface.co/docs/huggingface_hub/v0.22.2/en/index), and the [Hugging Face Inference API](https://huggingface.co/docs/api-inference/index).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  short_description: chat with gpt2-nepali
11
  ---
12
 
13
+ An example chatbot using [Gradio](https://gradio.app), [`huggingface_hub`](https://huggingface.co/docs/huggingface_hub/v0.22.2/en/index), and the [Hugging Face Inference API](https://huggingface.co/docs/api-inference/index).
14
+
15
+ # Gradio instructions
16
+
17
+ ```
18
+ # When prompted for a password, use an access token with write permissions.
19
+
20
+ # Generate one from your settings: https://huggingface.co/settings/tokens
21
+
22
+ git clone https://huggingface.co/spaces/Aananda-giri/gpt2-nepalis
23
+
24
+ # modify these files locally, then commit and push
25
+
26
+ git commit -am "Update space"
27
+ git push
28
+ ```
app.py CHANGED
@@ -1,64 +1,82 @@
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
27
 
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
-
62
-
63
- if __name__ == "__main__":
64
- demo.launch()
 
1
+ # app.py (second app by claude)
2
  import gradio as gr
3
+ import torch
4
+ from model import GPTModel
5
+ from transformers import PreTrainedTokenizerFast
6
+ from gpt_model_code import load_model_n_tokenizer, generate
7
+ # Load model and tokenizer once at startup
8
+ model, tokenizer = load_model_n_tokenizer()
9
+ model.eval()
10
 
11
+ def generate_text(prompt, max_new_tokens, top_k, top_p, temperature, repetition_penalty, penalize_len_below):
12
+ device = next(model.parameters()).device
13
+
14
+ # Convert top_k to None if using top_p
15
+ if top_p > 0:
16
+ top_k = None
17
+ else:
18
+ top_p = None
19
+
20
+ with torch.no_grad():
21
+ output_text = generate( # function uses `with torch.no_grad()` internally already
22
+ model=model,
23
+ prompt=prompt,
24
+ tokenizer=tokenizer,
25
+ max_new_tokens=max_new_tokens,
26
+ top_p=top_p,# top p sampling is prefered over top k if top_p != None
27
+ top_k=top_k,
28
+ temperature=0.7,
29
+ repetition_penalty=repetition_penalty, # New parameter: Repetition penalty factor
30
+ penalize_len_below=penalize_len_below # New parameter: Minimum content length for penalizing EOT token.
31
+ )
32
+
33
+ return output_text
34
 
35
+ # Create Gradio interface
36
+ with gr.Blocks(title="Nepali GPT-2 Text Generator") as interface:
37
+ gr.Markdown("# Nepali GPT-2 Text Generator")
38
+ gr.Markdown("Enter Nepali text to generate content using the custom GPT-2 model.")
39
+
40
+ with gr.Row():
41
+ with gr.Column():
42
+ prompt = gr.Textbox(label="Prompt", placeholder="Enter Nepali text here...")
43
+ max_tokens = gr.Slider(minimum=1, maximum=512, value=50, step=1, label="Max New Tokens")
44
+
45
+ with gr.Row():
46
+ with gr.Column():
47
+ top_k = gr.Slider(minimum=0, maximum=100, value=50, step=1, label="Top K (set to 0 to use Top P)")
48
+ temperature = gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Temperature")
49
+ with gr.Column():
50
+ top_p = gr.Slider(minimum=0, maximum=1.0, value=0, step=0.05, label="Top P (set above 0 to use instead of Top K)")
51
+ repetition_penalty = gr.Slider(minimum=1.0, maximum=2.0, value=1.2, step=0.1, label="Repetition Penalty")
52
+
53
+ min_length = gr.Slider(minimum=1, maximum=200, value=50, step=1, label="Minimum Length Penalty")
54
+ generate_btn = gr.Button("Generate Text")
55
+
56
+ with gr.Column():
57
+ output = gr.Textbox(label="Generated Text", lines=10)
58
+
59
+ # Add examples if you have any
60
+ gr.Examples(
61
+ examples=[
62
+ ["रामले भात खायो", 50, 50, 0, 0.7, 1.2, 50],
63
+ ["नेपाल एउटा", 100, 0, 0.9, 0.8, 1.2, 100],
64
+ ],
65
+ inputs=[prompt, max_tokens, top_k, top_p, temperature, repetition_penalty, min_length],
66
+ outputs=output,
67
+ fn=generate_text,
68
+ cache_examples=True,
69
+ )
70
+
71
+ generate_btn.click(
72
+ fn=generate_text,
73
+ inputs=[prompt, max_tokens, top_p, top_k, temperature, repetition_penalty, min_length],
74
+ outputs=output
75
+ )
76
 
 
 
 
 
 
 
 
 
 
77
 
78
+ '''
 
 
 
 
79
 
80
+ '''
81
 
82
+ interface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app_autogenerated_code.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from huggingface_hub import InferenceClient
3
+
4
+ """
5
+ For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
+ """
7
+ client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
+
9
+
10
+ def respond(
11
+ message,
12
+ history: list[tuple[str, str]],
13
+ system_message,
14
+ max_tokens,
15
+ temperature,
16
+ top_p,
17
+ ):
18
+ messages = [{"role": "system", "content": system_message}]
19
+
20
+ for val in history:
21
+ if val[0]:
22
+ messages.append({"role": "user", "content": val[0]})
23
+ if val[1]:
24
+ messages.append({"role": "assistant", "content": val[1]})
25
+
26
+ messages.append({"role": "user", "content": message})
27
+
28
+ response = ""
29
+
30
+ for message in client.chat_completion(
31
+ messages,
32
+ max_tokens=max_tokens,
33
+ stream=True,
34
+ temperature=temperature,
35
+ top_p=top_p,
36
+ ):
37
+ token = message.choices[0].delta.content
38
+
39
+ response += token
40
+ yield response
41
+
42
+
43
+ """
44
+ For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
+ """
46
+ demo = gr.ChatInterface(
47
+ respond,
48
+ additional_inputs=[
49
+ gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
+ gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
+ gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
+ gr.Slider(
53
+ minimum=0.1,
54
+ maximum=1.0,
55
+ value=0.95,
56
+ step=0.05,
57
+ label="Top-p (nucleus sampling)",
58
+ ),
59
+ ],
60
+ )
61
+
62
+
63
+ if __name__ == "__main__":
64
+ demo.launch()
app_by_claude.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ import gradio as gr
3
+ import torch
4
+ from model import GPTModel # Import your specific GPT model class
5
+ from transformers import PreTrainedTokenizerFast
6
+
7
+ # Load model and tokenizer once at startup
8
+ def load_model_n_tokenizer():
9
+ model = GPTModel.from_pretrained("Aananda-giri/GPT2-Nepali")
10
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
11
+ model.to(device)
12
+ tokenizer = PreTrainedTokenizerFast.from_pretrained("Aananda-giri/NepaliBPE")
13
+ return model, tokenizer
14
+
15
+ # Initialize at startup
16
+ model, tokenizer = load_model_n_tokenizer()
17
+ model.eval()
18
+
19
+ def generate(prompt, max_new_tokens, top_k, temperature, repetition_penalty, penalize_len_below):
20
+ device = next(model.parameters()).device
21
+
22
+ with torch.no_grad():
23
+ input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
24
+
25
+ outputs = model.generate(
26
+ input_ids,
27
+ max_new_tokens=max_new_tokens,
28
+ top_k=top_k,
29
+ temperature=temperature,
30
+ repetition_penalty=repetition_penalty,
31
+ min_length=penalize_len_below,
32
+ pad_token_id=tokenizer.pad_token_id,
33
+ eos_token_id=tokenizer.eos_token_id,
34
+ )
35
+
36
+ return tokenizer.decode(outputs[0], skip_special_tokens=True)
37
+
38
+ # Create Gradio interface
39
+ interface = gr.Interface(
40
+ fn=generate,
41
+ inputs=[
42
+ gr.Textbox(label="Prompt", placeholder="Enter Nepali text here..."),
43
+ gr.Slider(minimum=1, maximum=512, value=50, step=1, label="Max New Tokens"),
44
+ gr.Slider(minimum=1, maximum=100, value=3, step=1, label="Top K"),
45
+ gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Temperature"),
46
+ gr.Slider(minimum=1.0, maximum=2.0, value=1.2, step=0.1, label="Repetition Penalty"),
47
+ gr.Slider(minimum=1, maximum=200, value=50, step=1, label="Minimum Length Penalty"),
48
+ ],
49
+ outputs=gr.Textbox(label="Generated Text"),
50
+ title="Nepali GPT-2 Text Generator",
51
+ description="Enter Nepali text to generate content using the custom GPT-2 model."
52
+ )
53
+
54
+ interface.launch()