How to debug it - Segmentation fault (core dumped)
- User
How to debug it - Segmentation fault (core dumped)
- Assistant
- User
- Assistant
How to debug it - Segmentation fault (core dumped)
Debugging a "Segmentation fault (core dumped)" error can be challenging but is essential for identifying and fixing bugs in your code that cause illegal memory access. Here are steps and tools you might use to debug such an error:
gdb <binary> <core-dump-file>.bt (backtrace) to print a stack trace, which shows the call stack at the moment the segmentation fault occurred.print to inspect the values of variables at different points in your code.watch to set a watchpoint on variables that you suspect are being changed unexpectedly.-fsanitize=address to enable AddressSanitizer.printf/std::cout debugging to narrow down where the fault occurs.-Wall for GCC) and pay attention to the compiler's warnings.Debugging segmentation faults can be time-consuming, but systematically checking your code and using the right tools can help identify and solve these errors.
What could be the cause of segmentation error in this code -import numpy as np from langchain.embeddings import HuggingFaceEmbeddings from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.vectorstores import Chroma from langchain.document_loaders import PyPDFLoader from langchain import HuggingFacePipeline from langchain import PromptTemplate from langchain.chains import ConversationalRetrievalChain from langchain.memory import ConversationBufferWindowMemory from sentence_transformers import SentenceTransformer import gradio as gr #nltk.download() import torch from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, pipeline, TextStreamer
def create_multipage_pdf(text, filename='output.pdf', font_size=12, margin=50): # Split text into chunks that fit on one page chunks = [] chunk_size = 50 # Number of characters per chunk for i in range(0, len(text), chunk_size): chunks.append(text[i:i+chunk_size])
# Create PDF
c = canvas.Canvas(filename, pagesize=letter)
width, height = letter
y = height - margin
for chunk in chunks:
# Draw text
text_object = c.beginText(margin, y)
text_object.setFont("Helvetica", font_size)
text_object.textLines(chunk)
c.drawText(text_object)
# Update y position
y -= (font_size + 4) # Adjust spacing between lines
# Check if we need to start a new page
if y <= margin:
c.showPage()
y = height - margin
c.save()
#create_multipage_pdf(text, filename='document.pdf')
bnb_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=False)
model_id = "meta-llama/Llama-2-7b-chat-hf"
tokenizer = AutoTokenizer.from_pretrained(model_id) model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config = bnb_config,device_map={"":0}) streamer = TextStreamer(tokenizer)
import json import textwrap
B_INST, E_INST = "[INST]", "[/INST]"
B_SYS, E_SYS = "<>\n", "\n<>\n\n"
DEFAULT_SYSTEM_PROMPT = """
You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information."""
def get_prompt(instruction, new_system_prompt=DEFAULT_SYSTEM_PROMPT ): SYSTEM_PROMPT = B_SYS + new_system_prompt + E_SYS prompt_template = B_INST + SYSTEM_PROMPT + instruction + E_INST return prompt_template
loader = PyPDFLoader("document.pdf")
text_splitter = RecursiveCharacterTextSplitter( # Set a really small chunk size, just to show. chunk_size = 500, chunk_overlap = 20, length_function = len, )
pages = loader.load_and_split(text_splitter)
#embeddings = HuggingFaceEmbeddings(model_name="hkunlp/instructor-xl", model_kwargs={'device': 'cuda'}) embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2", model_kwargs={'device': 'cuda'})
db = Chroma.from_documents(pages, embedding=embeddings, persist_directory = '/content/db')
instruction = "Given the context that has been provided. \n {context}, Answer the following question - \n{question}"
system_prompt = """You are an honest virtual assistant. You will be given a context to answer from. In case you are sure you don't know the answer then you say that based on the context you don't know the answer. In all other instances you provide an answer to the best of your capability. Cite context when you can access them maintaining formatting. Don't say 'based on the context provided more than once."""
get_prompt(instruction, system_prompt)
"""## Setting up with LangChain"""
template = get_prompt(instruction, system_prompt) print(template)
prompt = PromptTemplate(template=template, input_variables=["context", "question"])
memory = ConversationBufferWindowMemory( memory_key="chat_history", k=5, return_messages=True )
retriever = db.as_retriever(search_kwargs={'k': 20})
def create_pipeline(max_new_tokens=1024): pipe = pipeline("text-generation", model=model, tokenizer = tokenizer, max_new_tokens = max_new_tokens, temperature = 0.6, streamer=streamer) return pipe
class ChessBot:
def init(self, memory, prompt, task:str = "text-generation", retriever = retriever): self.memory = memory self.prompt = prompt self.retriever = retriever
def create_chat_bot(self, max_new_tokens = 1024): hf_pipe = create_pipeline(max_new_tokens) llm = HuggingFacePipeline(pipeline =hf_pipe) qa = ConversationalRetrievalChain.from_llm( llm=llm, retriever=self.retriever, memory=self.memory, combine_docs_chain_kwargs={"prompt": self.prompt} ) return qa
chess_bot = ChessBot(memory = memory, prompt = prompt)
bot = chess_bot.create_chat_bot()
def clear_llm_memory(): bot.memory.clear()
def update_prompt(sys_prompt): if sys_prompt == "": sys_prompt = system_prompt template = get_prompt(instruction, sys_prompt)
prompt = PromptTemplate(template=template, input_variables=["context", "question"])
bot.combine_docs_chain.llm_chain.prompt = prompt
"""1. Not using API 2. Use cases are not defined 3. Just a POC emphasis """
with gr.Blocks() as demo: gr.Markdown( """ # SDS HR-BOT Demo Version Please ask questions related to Employee Leave Policy! """) # Commenting update prompt option #update_sys_prompt = gr.Textbox(label = "Update System Prompt") chatbot = gr.Chatbot(label="SAMSUNG SDS", height = 300) msg = gr.Textbox(label = "Question") clear = gr.ClearButton([msg, chatbot]) clear_memory = gr.Button(value = "Clear LLM Memory")
def respond(message, chat_history):
bot_message = bot({"question": message})['answer']
chat_history.append((message, bot_message))
return "", chat_history
msg.submit(respond, inputs=[msg, chatbot], outputs=[msg, chatbot])
clear_memory.click(clear_llm_memory)
# Commenting update prompt option
#update_sys_prompt.submit(update_prompt, inputs=update_sys_prompt)
demo.launch(share=False, server_name='216.48.177.144', server_port=8501)
Debugging segmentation faults in a complex application involving multiple libraries like in your Python script can be tricky. The provided code integrates various components such as transformers, gradio, and langchain, among others. Segmentation faults in Python are often due to issues in the underlying C or C++ code called by Python libraries, rather than Python code itself. Here's how you might approach diagnosing and resolving the segmentation fault:
Try to narrow down which part of the code causes the segmentation fault. You can do this by:
Given the libraries and features your code uses, consider these common causes:
transformers, gradio, torch, and any other libraries are compatible with each other.model_kwargs={'device': 'cuda'} which indicates GPU usage. Issues can arise from improper allocation or access to GPU memory. Make sure your CUDA setup (drivers, version) is compatible with the versions of PyTorch you are using.torch and transformers might have bugs or incompatibilities with your system. Ensure all such libraries are up to date.gdb python core
transformers, gradio, torch, sentence_transformers, and other libraries for similar problems reported by other users. Someone might have already encountered and solved this issue.canvas object), but some required imports like from reportlab.pdfgen import canvas and from reportlab.lib.pagesizes import letter are missing. Ensure all external resources and libraries are properly included and used.AutoModelForCausalLM.from_pretrained and ensure that the model ID is correct and compatible with the quantization and other options you're using.Ultimately, because segmentation faults are indicative of lower-level errors, the resolution often involves closely checking library use, environments, and sometimes the interaction between Python and system-level resources.
Not yet included in a published release.