j-silv commited on
Commit
af5c6d3
·
0 Parent(s):

Add initial code for LLM to output text

Browse files

Just the scaffolding for now. Showing system and user prompt
on the Streamlit app, and then a random sample button and
the LLM output response.

Files changed (8) hide show
  1. .gitignore +1 -0
  2. LICENSE +8 -0
  3. README.md +21 -0
  4. autohdl/__init__.py +0 -0
  5. autohdl/data.py +49 -0
  6. autohdl/llm.py +43 -0
  7. requirements.txt +4 -0
  8. server.py +70 -0
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ __pycache__
LICENSE ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ Copyright 2025-Present Justin Silver
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
8
+
README.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AutoHDL
2
+
3
+ AI agent which generates Verilog code
4
+
5
+ This project is a work-in-progress!
6
+
7
+ ## Introduction
8
+
9
+ This is an attempt to build an AI agent which tries to generate syntactically correct
10
+ Verilog code from input text specifications.
11
+
12
+ When I'm done, the LLM will be able to call Verilog linter and simulation tools.
13
+ It will then use the tools output to self-correct the Verilog code it suggests.
14
+
15
+ For testing and illustration purposes, I'm using the MG-Verilog dataset from Georgia Tech.
16
+
17
+ ## Tools
18
+
19
+ - `transformers` for LLM calls
20
+ - `outlines` for structured LLM output
21
+ - `streamlit` for pipeline visualization
autohdl/__init__.py ADDED
File without changes
autohdl/data.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from datasets import load_dataset
3
+
4
+ def extract_description(prompt):
5
+ """Use regex to extract description from prompt
6
+
7
+ The MG-verilog dataset comes with the special tokens such as
8
+ [INST], <<SYS>>, etc. This removes those and only extracts
9
+ the description and verilog module header. We do this
10
+ so that we can use models with different chat templates.
11
+ """
12
+
13
+ sysend_re = re.compile(r"<<\/SYS>>", re.MULTILINE)
14
+ instend_re = re.compile(r"\[\/INST\]", re.MULTILINE)
15
+
16
+ try:
17
+ sysend_pos = re.search(sysend_re, prompt).end()
18
+ instend_pos = re.search(instend_re, prompt).start()
19
+ except:
20
+ raise Exception("Prompt is not in expected format when extracting description")
21
+
22
+ return prompt[sysend_pos:instend_pos].strip()
23
+
24
+ def replace_template(batch):
25
+ """Remove system prompt and add raw description text to all summaries"""
26
+
27
+ for batch_idx in range(len(batch['description'])):
28
+ descriptions = batch['description'][batch_idx]
29
+
30
+ for summary_type in descriptions:
31
+ descriptions[summary_type] = extract_description(descriptions[summary_type])
32
+ return batch
33
+
34
+
35
+ def data(name="GaTech-EIC/MG-Verilog", batch_size=4, small_dataset=True):
36
+ """Load MG-Verilog dataset from GAtech paper
37
+
38
+ https://arxiv.org/pdf/2407.01910
39
+ """
40
+
41
+ ds = load_dataset(name, split=f"train[:{10 if small_dataset else ''}]")
42
+ ds = ds.map(replace_template, batched=True, batch_size=batch_size)
43
+
44
+ return ds
45
+
46
+
47
+ if __name__ == "__main__":
48
+ data()
49
+
autohdl/llm.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import outlines
2
+ from outlines.inputs import Chat
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
4
+ from .data import data
5
+
6
+ system_prompt = ("You only complete chats with syntax correct Verilog code. "
7
+ "End the Verilog module code completion with 'endmodule'. "
8
+ "Do not include module, input and output definitions.")
9
+
10
+ class LLM:
11
+ def __init__(self):
12
+ self.system_prompt = system_prompt
13
+
14
+ def load_model(self, use_cpu=True):
15
+ if use_cpu:
16
+ model_name = "HuggingFaceTB/SmolLM2-360M-Instruct"
17
+ self.device = "cpu"
18
+ else:
19
+ model_name = "codellama/CodeLlama-7b-Instruct-hf"
20
+ self.device = "cuda"
21
+
22
+ self.hf_tokenizer = AutoTokenizer.from_pretrained(model_name)
23
+ self.hf_model = AutoModelForCausalLM.from_pretrained(model_name)
24
+
25
+ return self.hf_tokenizer, self.hf_model
26
+
27
+ def __call__(self, description_prompt):
28
+
29
+ messages = [
30
+ {"role": "system", "content": self.system_prompt},
31
+ {"role": "user", "content": description_prompt}
32
+ ]
33
+
34
+ input_text=self.hf_tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
35
+ # print(input_text)
36
+
37
+ inputs = self.hf_tokenizer.encode(input_text, return_tensors="pt").to(self.device)
38
+
39
+ outputs = self.hf_model.generate(inputs)
40
+
41
+ # print(self.hf_tokenizer.decode(outputs[0]))
42
+ return self.hf_tokenizer.decode(outputs[0])
43
+
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ transformers
2
+ datasets
3
+ outlines[transformers]
4
+ streamlit
server.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from autohdl.data import data
3
+ from autohdl.llm import system_prompt, LLM
4
+ import random
5
+
6
+ """
7
+ # AutoHDL
8
+ ### AI agent which generates Verilog code
9
+ """
10
+
11
+ def random_sample_btn(stop):
12
+ """Generate a new sample"""
13
+
14
+ idx = random.randrange(stop)
15
+ st.session_state['idx'] = idx
16
+ print(idx)
17
+ return idx
18
+
19
+ def generate_btn(model, text):
20
+ st.session_state['response'] = model(text)
21
+ return st.session_state['response']
22
+
23
+ @st.cache_resource(show_spinner="Loading LLM...")
24
+ def load_model():
25
+ model = LLM()
26
+ model.load_model()
27
+ return model
28
+
29
+
30
+ def server():
31
+ ds = data(small_dataset=True)
32
+
33
+ model = load_model()
34
+
35
+ if 'idx' not in st.session_state:
36
+ st.session_state['idx'] = 0
37
+
38
+ if 'response' not in st.session_state:
39
+ st.session_state['response'] = "Click generate for LLM to respond"
40
+
41
+ idx = st.session_state['idx']
42
+
43
+ summary = "high_level_global_summary"
44
+
45
+ st.text_area("System prompt",
46
+ system_prompt,
47
+ height="content")
48
+
49
+ description_prompt = ds['description'][idx][summary]
50
+
51
+ st.text_area("User prompt",
52
+ description_prompt,
53
+ height=200)
54
+
55
+ st.text_area("Expected response",
56
+ ds['code'][idx],
57
+ height=200)
58
+
59
+ st.button("Random sample", on_click=random_sample_btn, args=[ds.num_rows])
60
+
61
+ st.text_area("LLM response",
62
+ st.session_state['response'],
63
+ disabled=True,
64
+ height=200)
65
+
66
+ st.button("Generate", on_click=generate_btn, args=[model, ds['description'][idx][summary]])
67
+
68
+
69
+ if __name__ == "__main__":
70
+ server()