# Cannot copy out of meta tensor; no data!

**URL:** </static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fcannot-copy-out-of-meta-tensor-no-data%2F128996%3E%5C
**Category:** 🤗Transformers\
**Created:** [December 3, 2024, 6:42am UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fcannot-copy-out-of-meta-tensor-no-data%2F128996 "2024-12-03T06:42:06Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![hawkiyc](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/hawkiyc/32/33085_2.png) [@hawkiyc](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2Fhawkiyc)%5C
**Post date:** [December 3, 2024, 6:42am UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fcannot-copy-out-of-meta-tensor-no-data%2F128996%2F1 "2024-12-03T06:42:06Z")

</div>

Hi Developers,

I have finetuned a Llama-3.1-8b-Instruct model; everything is fine in the fine-tuning stage. However, I often get the following error message when I deploy my model with langchain.

Here is the error message

```auto
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty() instead of torch.nn.Module.to() when moving module from meta to a different device.
Traceback:
File "/home/revlis_ai/anaconda3/envs/env_llm/lib/python3.8/site-packages/streamlit/runtime/scriptrunner/exec_code.py", line 88, in exec_func_with_error_handling
    result = func()
File "/home/revlis_ai/anaconda3/envs/env_llm/lib/python3.8/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 579, in code_to_exec
    exec(code, module. __dict__ )
File "/home/revlis_ai/Documents/llm_practise/lora_finetune_llm/app3.py", line 50, in <module>
    model = AutoModelForCausalLM.from_pretrained(
File "/home/revlis_ai/anaconda3/envs/env_llm/lib/python3.8/site-packages/transformers/models/auto/auto_factory.py", line 564, in from_pretrained
    return model_class.from_pretrained(
File "/home/revlis_ai/anaconda3/envs/env_llm/lib/python3.8/site-packages/transformers/modeling_utils.py", line 4310, in from_pretrained
    model.load_adapter(
File "/home/revlis_ai/anaconda3/envs/env_llm/lib/python3.8/site-packages/transformers/integrations/peft.py", line 214, in load_adapter
    inject_adapter_in_model(peft_config, self, adapter_name, **peft_load_kwargs)
File "/home/revlis_ai/anaconda3/envs/env_llm/lib/python3.8/site-packages/peft/mapping.py", line 227, in inject_adapter_in_model
    peft_model = tuner_cls(model, peft_config, adapter_name=adapter_name, low_cpu_mem_usage=low_cpu_mem_usage)
File "/home/revlis_ai/anaconda3/envs/env_llm/lib/python3.8/site-packages/peft/tuners/lora/model.py", line 141, in __init__
    super(). __init__ (model, config, adapter_name, low_cpu_mem_usage=low_cpu_mem_usage)
File "/home/revlis_ai/anaconda3/envs/env_llm/lib/python3.8/site-packages/peft/tuners/tuners_utils.py", line 184, in __init__
    self.inject_adapter(self.model, adapter_name, low_cpu_mem_usage=low_cpu_mem_usage)
File "/home/revlis_ai/anaconda3/envs/env_llm/lib/python3.8/site-packages/peft/tuners/tuners_utils.py", line 496, in inject_adapter
    self._create_and_replace(peft_config, adapter_name, target, target_name, parent, current_key=key)
File "/home/revlis_ai/anaconda3/envs/env_llm/lib/python3.8/site-packages/peft/tuners/lora/model.py", line 230, in _create_and_replace
    self._replace_module(parent, target_name, new_module, target)
File "/home/revlis_ai/anaconda3/envs/env_llm/lib/python3.8/site-packages/peft/tuners/lora/model.py", line 254, in _replace_module
    new_module.to(child.weight.device)
File "/home/revlis_ai/anaconda3/envs/env_llm/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1174, in to
    return self._apply(convert)
File "/home/revlis_ai/anaconda3/envs/env_llm/lib/python3.8/site-packages/torch/nn/modules/module.py", line 780, in _apply
    module._apply(fn)
File "/home/revlis_ai/anaconda3/envs/env_llm/lib/python3.8/site-packages/torch/nn/modules/module.py", line 780, in _apply
    module._apply(fn)
File "/home/revlis_ai/anaconda3/envs/env_llm/lib/python3.8/site-packages/torch/nn/modules/module.py", line 805, in _apply
    param_applied = fn(param)
File "/home/revlis_ai/anaconda3/envs/env_llm/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1167, in convert
    raise NotImplementedError(

```

And here is my code

```auto
#%% Import Libraries

import streamlit as st
from uuid import uuid4
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain.chains import create_retrieval_chain, create_history_aware_retriever
from langchain.chains.combine_documents import create_stuff_documents_chain
from langchain_community.vectorstores import FAISS
from langchain_community.chat_message_histories import ChatMessageHistory
from langchain_core.chat_history import BaseChatMessageHistory
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_huggingface import HuggingFaceEmbeddings, HuggingFacePipeline, ChatHuggingFace
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline, BitsAndBytesConfig, TextStreamer
from langchain_community.document_loaders import PyPDFLoader
from langchain_core.runnables.history import RunnableWithMessageHistory
import torch
import os
from pathlib import Path
from dotenv import load_dotenv

#%% Get Correct Path

current_dir = Path( __file__ ).parent.absolute()
doc_dir = os.path.join(current_dir, "research_papers")
db_path = os.path.join(current_dir, "FAISS_DB")

#%% Load API Key

if 'STREAMLIT_PUBLIC_PATH' in os.environ:
    os.environ["HF_TOKEN"] = st.secrets['HUGGINGFACE_TOKEN']
else:
    load_dotenv()
    os.environ["HF_TOKEN"] = os.getenv('HUGGINGFACE_TOKEN')

#%% Load LLM and Embedding

embeddings = HuggingFaceEmbeddings(
    model_name='all-MiniLM-L6-v2',)

# bnb_config = BitsAndBytesConfig(
# load_in_4bit = True, 
# bnb_4bit_quant_type = "nf4", 
# bnb_4bit_compute_dtype = torch.bfloat16,
# bnb_4bit_use_double_quant = True,)
bnb_config = BitsAndBytesConfig(
    load_in_8bit = True,)
tokenizer = AutoTokenizer.from_pretrained(
    "./lora_finetune_llm/llm_finetune/checkpoint-2571")
streamer = TextStreamer(tokenizer)
model = AutoModelForCausalLM.from_pretrained(
    "./lora_finetune_llm/llm_finetune/checkpoint-2571", 
    quantization_config = bnb_config)

llm_pipeline = pipeline(
    "text-generation", 
    model = model, 
    tokenizer = tokenizer, 
    streamer = streamer,
    torch_dtype = torch.bfloat16,
    temperature = 0.15,
    top_p = .15,
    max_new_tokens = 512,
    trust_remote_code = True,
    return_full_text = False,)
hf_pipeline = HuggingFacePipeline(pipeline=llm_pipeline)
llm = ChatHuggingFace(llm=hf_pipeline, tokenizer=hf_pipeline.pipeline.tokenizer)

#%% Initialize session state

if 'conversations' not in st.session_state:
    st.session_state.conversations = {}
    st.session_state.current_session = None
    st.session_state.session_history = {}

#%% Build Streamlit APP

st.title('ChatBot Q&A with RAG')
st.sidebar.title("Conversations")

def new_chat():
    session_id = str(uuid4()).replace('-', '')
    st.session_state.conversations[session_id] = {
        "history": ChatMessageHistory(),
        "uploaded_files": []}
    st.session_state.current_session = session_id

if not st.session_state.conversations:
    new_chat()

if st.sidebar.button("New Chat"):
    new_chat()

session_ids = list(st.session_state.conversations.keys())
session_names = [f"Session {i+1}" for i in range(len(session_ids))]
selected_session = st.sidebar.radio(
    "Select Conversation",
    session_names,
    index=session_ids.index(st.session_state.current_session))

if selected_session:
    selected_index = session_names.index(selected_session)
    st.session_state.current_session = session_ids[selected_index]

current_session = st.session_state.current_session
conversation_data = st.session_state.conversations[current_session]

uploaded_files = st.file_uploader(
    'Upload PDF Files',
    type=['pdf'],
    accept_multiple_files=True,
    key=st.session_state.current_session)

def get_session_history(session_id: str) -> BaseChatMessageHistory:
    return st.session_state.conversations[session_id]["history"]

if uploaded_files:
    documents = []
    for f in uploaded_files:
        if f.name not in conversation_data["uploaded_files"]:
            conversation_data["uploaded_files"].append(f.name)
            temp = './temp.pdf'
            with open(temp, 'wb') as file:
                file.write(f.getvalue())
            loader = PyPDFLoader(temp)
            doc = loader.load()
            documents.extend(doc)
            os.remove(temp)

    splitter = RecursiveCharacterTextSplitter(chunk_size=5140, chunk_overlap=512)

    try:
        st.write('Trying to load FAISS BD')
        faiss_db = FAISS.load_local(
            db_path + f"/{current_session}", 
            embeddings, 
            allow_dangerous_deserialization = True)
        if documents:
            st.write('Detect new file(s) upload, add docs into Chroma DB')
            chunked_documents = splitter.split_documents(documents)
            faiss_db.add_documents(chunked_documents)
            faiss_db.save_local(db_path + f"/{current_session}")    
        st.write('FAISS DB loaded!!!')
    except:
        st.write('No FAISS DB found, creating FAISS DB.......')
        chunked_documents = splitter.split_documents(documents)
        faiss_db = FAISS.from_documents(chunked_documents, embeddings)
        faiss_db.save_local(db_path + f"/{current_session}")
        st.write('FAISS DB Created!!!')

st.write(f"Uploaded Files: {conversation_data['uploaded_files']}")

user_input = st.text_area("Ask me your question:", key="input_text",)
if st.button("Submit"):
    if user_input:

        faiss_db = FAISS.load_local(
            db_path + f"/{current_session}", 
            embeddings, 
            allow_dangerous_deserialization = True)
        retriever = faiss_db.as_retriever()

        contextual_sys_prompt = '''
            Given a chat history and the latest user question which might reference context in the chat history, 
            formulate a standalone question which can be understood without the chat history. Do NOT answer the question, 
            just reformulate it if needed and otherwise return it as is.'''
        contextual_prompt = ChatPromptTemplate.from_messages(
            [('system', contextual_sys_prompt),
                MessagesPlaceholder('chat_history'),
                ('human', '{input}')])
        history_aware_retriever = create_history_aware_retriever(llm, retriever, contextual_prompt)

        sys_prompt = '''
            You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. 
            If you don't know the answer, say that you don't know. Use three sentences maximum and keep the answer concise.
            \n\n
            {context}'''
        qa_prompt = ChatPromptTemplate.from_messages(
            [('system', sys_prompt),
                MessagesPlaceholder('chat_history'),
                ('human', '{input}')])

        qa_chain = create_stuff_documents_chain(llm, qa_prompt)
        rag_chain = create_retrieval_chain(history_aware_retriever, qa_chain)

        conversational_rag_chain = RunnableWithMessageHistory(
            rag_chain,
            get_session_history,
            input_messages_key="input",
            history_messages_key="chat_history",
            output_messages_key="answer",)
        st.session_state.session_history[current_session] = get_session_history(current_session)
        with torch.autocast("cuda"):
            ans = conversational_rag_chain.invoke(
                {'input': user_input},
                config={'configurable': {'session_id': current_session}})
        st.write("Assistant:", ans['answer'])

if current_session in st.session_state.session_history:
    st.write("Chat History:")
    for message in st.session_state.session_history[current_session].messages:
        st.write(f"Role: {message.type}, Content: {message.content}")
else:
    st.write("No chat history available.")

```

I also tested the open-sourced Llama from Meta with the following setting, and this issue happens, too.

```auto
bnb_config = BitsAndBytesConfig(
    load_in_8bit = True, )
tokenizer = AutoTokenizer.from_pretrained(
    "meta-llama/Llama-3.1-8B-Instruct", )
streamer = TextStreamer(tokenizer)
model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-3.1-8B-Instruct",
    quantization_config = bnb_config,)

```

---

<div class="post-metadata">

**Author:** ![saeed899](https://avatars.discourse-cdn.com/v4/letter/s/3da27b/32.png) [@saeed899](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2Fsaeed899)%5C
**Post date:** [January 4, 2025, 10:19pm UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fcannot-copy-out-of-meta-tensor-no-data%2F128996%2F2 "2025-01-04T22:19:56Z")

</div>

Same problem!

---

<div class="post-metadata">

**Author:** ![juyil](https://avatars.discourse-cdn.com/v4/letter/j/a87d85/32.png) [@juyil](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2Fjuyil)%5C
**Post date:** [February 28, 2025, 2:42am UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fcannot-copy-out-of-meta-tensor-no-data%2F128996%2F3 "2025-02-28T02:42:18Z")

</div>

Same problem

---

<div class="post-metadata">

**Author:** ![John6666](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/john6666/32/27664_2.png) [@John6666](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2FJohn6666)%5C
**Post date:** [February 28, 2025, 4:53am UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fcannot-copy-out-of-meta-tensor-no-data%2F128996%2F4 "2025-02-28T04:53:06Z")

</div>

It’s probably an unsolved issue. By the way, this error will also occur even if it’s not an issue, but in that case it’s a failure like the latter. However, it doesn’t seem to be an easy mistake this time.

> <https://github.com/langchain-ai/langchain/issues/28497>
>
> \### Checked other resources
> 
> \- \[X\] I added a very descriptive title to this issu…e.
> \- \[X\] I searched the LangChain documentation with the integrated search.
> \- \[X\] I used the GitHub search to find a similar question and didn't find it.
> \- \[X\] I am sure that this is a bug in LangChain rather than my code.
> \- \[X\] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package).
> 
> \### Example Code
> 
> \`\`\`python
> \#%% Import Libraries
> 
> import streamlit as st
> from uuid import uuid4
> from langchain\_text\_splitters import RecursiveCharacterTextSplitter
> from langchain.chains import create\_retrieval\_chain, create\_history\_aware\_retriever
> from langchain.chains.combine\_documents import create\_stuff\_documents\_chain
> from langchain\_community.vectorstores import FAISS
> from langchain\_community.chat\_message\_histories import ChatMessageHistory
> from langchain\_core.chat\_history import BaseChatMessageHistory
> from langchain\_core.prompts import ChatPromptTemplate, MessagesPlaceholder
> from langchain\_huggingface import HuggingFaceEmbeddings, HuggingFacePipeline, ChatHuggingFace
> from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline, BitsAndBytesConfig, TextStreamer
> from langchain\_community.document\_loaders import PyPDFLoader
> from langchain\_core.runnables.history import RunnableWithMessageHistory
> import torch
> import os
> from pathlib import Path
> from dotenv import load\_dotenv
> 
> \#%% Get Correct Path
> 
> current\_dir = Path(\_\_file\_\_).parent.absolute()
> doc\_dir = os.path.join(current\_dir, "research\_papers")
> db\_path = os.path.join(current\_dir, "FAISS\_DB")
> 
> \#%% Load API Key
> 
> if 'STREAMLIT\_PUBLIC\_PATH' in os.environ:
> os.environ\["HF\_TOKEN"\] = st.secrets\['HUGGINGFACE\_TOKEN'\]
> else:
> load\_dotenv()
> os.environ\["HF\_TOKEN"\] = os.getenv('HUGGINGFACE\_TOKEN')
> 
> \#%% Load LLM and Embedding
> 
> embeddings = HuggingFaceEmbeddings(
> model\_name='all-MiniLM-L6-v2',)
> 
> \# bnb\_config = BitsAndBytesConfig(
> \# load\_in\_4bit = True, 
> \# bnb\_4bit\_quant\_type = "nf4", 
> \# bnb\_4bit\_compute\_dtype = torch.bfloat16,
> \# bnb\_4bit\_use\_double\_quant = True,)
> bnb\_config = BitsAndBytesConfig(
> load\_in\_8bit = True,)
> tokenizer = AutoTokenizer.from\_pretrained(
> "./lora\_finetune\_llm/llm\_finetune/checkpoint-2571")
> streamer = TextStreamer(tokenizer)
> model = AutoModelForCausalLM.from\_pretrained(
> "./lora\_finetune\_llm/llm\_finetune/checkpoint-2571", 
> quantization\_config = bnb\_config)
> 
> llm\_pipeline = pipeline(
> "text-generation", 
> model = model, 
> tokenizer = tokenizer, 
> streamer = streamer,
> torch\_dtype = torch.bfloat16,
> temperature = 0.15,
> top\_p = .15,
> max\_new\_tokens = 512,
> trust\_remote\_code = True,
> return\_full\_text = False,)
> hf\_pipeline = HuggingFacePipeline(pipeline=llm\_pipeline)
> llm = ChatHuggingFace(llm=hf\_pipeline, tokenizer=hf\_pipeline.pipeline.tokenizer)
> 
> \#%% Initialize session state
> 
> if 'conversations' not in st.session\_state:
> st.session\_state.conversations = {}
> st.session\_state.current\_session = None
> st.session\_state.session\_history = {}
> 
> \#%% Build Streamlit APP
> 
> st.title('ChatBot Q&A with RAG')
> st.sidebar.title("Conversations")
> 
> def new\_chat():
> session\_id = str(uuid4()).replace('-', '')
> st.session\_state.conversations\[session\_id\] = {
> "history": ChatMessageHistory(),
> "uploaded\_files": \[\]}
> st.session\_state.current\_session = session\_id
> 
> if not st.session\_state.conversations:
> new\_chat()
> 
> if st.sidebar.button("New Chat"):
> new\_chat()
> 
> session\_ids = list(st.session\_state.conversations.keys())
> session\_names = \[f"Session {i+1}" for i in range(len(session\_ids))\]
> selected\_session = st.sidebar.radio(
> "Select Conversation",
> session\_names,
> index=session\_ids.index(st.session\_state.current\_session))
> 
> if selected\_session:
> selected\_index = session\_names.index(selected\_session)
> st.session\_state.current\_session = session\_ids\[selected\_index\]
> 
> current\_session = st.session\_state.current\_session
> conversation\_data = st.session\_state.conversations\[current\_session\]
> 
> uploaded\_files = st.file\_uploader(
> 'Upload PDF Files',
> type=\['pdf'\],
> accept\_multiple\_files=True,
> key=st.session\_state.current\_session)
> 
> def get\_session\_history(session\_id: str) -\> BaseChatMessageHistory:
> return st.session\_state.conversations\[session\_id\]\["history"\]
> 
> if uploaded\_files:
> documents = \[\]
> for f in uploaded\_files:
> if f.name not in conversation\_data\["uploaded\_files"\]:
> conversation\_data\["uploaded\_files"\].append(f.name)
> temp = './temp.pdf'
> with open(temp, 'wb') as file:
> file.write(f.getvalue())
> loader = PyPDFLoader(temp)
> doc = loader.load()
> documents.extend(doc)
> os.remove(temp)
> 
> splitter = RecursiveCharacterTextSplitter(chunk\_size=5140, chunk\_overlap=512)
> 
> try:
> st.write('Trying to load FAISS BD')
> faiss\_db = FAISS.load\_local(
> db\_path + f"/{current\_session}", 
> embeddings, 
> allow\_dangerous\_deserialization = True)
> if documents:
> st.write('Detect new file(s) upload, add docs into Chroma DB')
> chunked\_documents = splitter.split\_documents(documents)
> faiss\_db.add\_documents(chunked\_documents)
> faiss\_db.save\_local(db\_path + f"/{current\_session}")    
> st.write('FAISS DB loaded!!!')
> except:
> st.write('No FAISS DB found, creating FAISS DB.......')
> chunked\_documents = splitter.split\_documents(documents)
> faiss\_db = FAISS.from\_documents(chunked\_documents, embeddings)
> faiss\_db.save\_local(db\_path + f"/{current\_session}")
> st.write('FAISS DB Created!!!')
> 
> st.write(f"Uploaded Files: {conversation\_data\['uploaded\_files'\]}")
> 
> user\_input = st.text\_area("Ask me your question:", key="input\_text",)
> if st.button("Submit"):
> if user\_input:
> 
> faiss\_db = FAISS.load\_local(
> db\_path + f"/{current\_session}", 
> embeddings, 
> allow\_dangerous\_deserialization = True)
> retriever = faiss\_db.as\_retriever()
> 
> contextual\_sys\_prompt = '''
> Given a chat history and the latest user question which might reference context in the chat history, 
> formulate a standalone question which can be understood without the chat history. Do NOT answer the question, 
> just reformulate it if needed and otherwise return it as is.'''
> contextual\_prompt = ChatPromptTemplate.from\_messages(
> \[('system', contextual\_sys\_prompt),
> MessagesPlaceholder('chat\_history'),
> ('human', '{input}')\])
> history\_aware\_retriever = create\_history\_aware\_retriever(llm, retriever, contextual\_prompt)
> 
> sys\_prompt = '''
> You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. 
> If you don't know the answer, say that you don't know. Use three sentences maximum and keep the answer concise.
> \\n\\n
> {context}'''
> qa\_prompt = ChatPromptTemplate.from\_messages(
> \[('system', sys\_prompt),
> MessagesPlaceholder('chat\_history'),
> ('human', '{input}')\])
> 
> qa\_chain = create\_stuff\_documents\_chain(llm, qa\_prompt)
> rag\_chain = create\_retrieval\_chain(history\_aware\_retriever, qa\_chain)
> 
> conversational\_rag\_chain = RunnableWithMessageHistory(
> rag\_chain,
> get\_session\_history,
> input\_messages\_key="input",
> history\_messages\_key="chat\_history",
> output\_messages\_key="answer",)
> st.session\_state.session\_history\[current\_session\] = get\_session\_history(current\_session)
> with torch.autocast("cuda"):
> ans = conversational\_rag\_chain.invoke(
> {'input': user\_input},
> config={'configurable': {'session\_id': current\_session}})
> st.write("Assistant:", ans\['answer'\])
> 
> if current\_session in st.session\_state.session\_history:
> st.write("Chat History:")
> for message in st.session\_state.session\_history\[current\_session\].messages:
> st.write(f"Role: {message.type}, Content: {message.content}")
> else:
> st.write("No chat history available.")
> \`\`\`
> 
> \### Error Message and Stack Trace (if applicable)
> 
> \`\`\`
> NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to\_empty() instead of torch.nn.Module.to() when moving module from meta to a different device.
> Traceback:
> File "/home/revlis\_ai/anaconda3/envs/env\_llm/lib/python3.8/site-packages/streamlit/runtime/scriptrunner/exec\_code.py", line 88, in exec\_func\_with\_error\_handling
> result = func()
> File "/home/revlis\_ai/anaconda3/envs/env\_llm/lib/python3.8/site-packages/streamlit/runtime/scriptrunner/script\_runner.py", line 579, in code\_to\_exec
> exec(code, module.\_\_dict\_\_)
> File "/home/revlis\_ai/Documents/llm\_practise/lora\_finetune\_llm/app3.py", line 50, in \<module\>
> model = AutoModelForCausalLM.from\_pretrained(
> File "/home/revlis\_ai/anaconda3/envs/env\_llm/lib/python3.8/site-packages/transformers/models/auto/auto\_factory.py", line 564, in from\_pretrained
> return model\_class.from\_pretrained(
> File "/home/revlis\_ai/anaconda3/envs/env\_llm/lib/python3.8/site-packages/transformers/modeling\_utils.py", line 4310, in from\_pretrained
> model.load\_adapter(
> File "/home/revlis\_ai/anaconda3/envs/env\_llm/lib/python3.8/site-packages/transformers/integrations/peft.py", line 214, in load\_adapter
> inject\_adapter\_in\_model(peft\_config, self, adapter\_name, \*\*peft\_load\_kwargs)
> File "/home/revlis\_ai/anaconda3/envs/env\_llm/lib/python3.8/site-packages/peft/mapping.py", line 227, in inject\_adapter\_in\_model
> peft\_model = tuner\_cls(model, peft\_config, adapter\_name=adapter\_name, low\_cpu\_mem\_usage=low\_cpu\_mem\_usage)
> File "/home/revlis\_ai/anaconda3/envs/env\_llm/lib/python3.8/site-packages/peft/tuners/lora/model.py", line 141, in \_\_init\_\_
> super().\_\_init\_\_(model, config, adapter\_name, low\_cpu\_mem\_usage=low\_cpu\_mem\_usage)
> File "/home/revlis\_ai/anaconda3/envs/env\_llm/lib/python3.8/site-packages/peft/tuners/tuners\_utils.py", line 184, in \_\_init\_\_
> self.inject\_adapter(self.model, adapter\_name, low\_cpu\_mem\_usage=low\_cpu\_mem\_usage)
> File "/home/revlis\_ai/anaconda3/envs/env\_llm/lib/python3.8/site-packages/peft/tuners/tuners\_utils.py", line 496, in inject\_adapter
> self.\_create\_and\_replace(peft\_config, adapter\_name, target, target\_name, parent, current\_key=key)
> File "/home/revlis\_ai/anaconda3/envs/env\_llm/lib/python3.8/site-packages/peft/tuners/lora/model.py", line 230, in \_create\_and\_replace
> self.\_replace\_module(parent, target\_name, new\_module, target)
> File "/home/revlis\_ai/anaconda3/envs/env\_llm/lib/python3.8/site-packages/peft/tuners/lora/model.py", line 254, in \_replace\_module
> new\_module.to(child.weight.device)
> File "/home/revlis\_ai/anaconda3/envs/env\_llm/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1174, in to
> return self.\_apply(convert)
> File "/home/revlis\_ai/anaconda3/envs/env\_llm/lib/python3.8/site-packages/torch/nn/modules/module.py", line 780, in \_apply
> module.\_apply(fn)
> File "/home/revlis\_ai/anaconda3/envs/env\_llm/lib/python3.8/site-packages/torch/nn/modules/module.py", line 780, in \_apply
> module.\_apply(fn)
> File "/home/revlis\_ai/anaconda3/envs/env\_llm/lib/python3.8/site-packages/torch/nn/modules/module.py", line 805, in \_apply
> param\_applied = fn(param)
> File "/home/revlis\_ai/anaconda3/envs/env\_llm/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1167, in convert
> raise NotImplementedError(
> \`\`\`
> 
> \### Description
> 
> Hi Developers,
> 
> I have finetuned a Llama-3.1-8b-Instruct model; everything is fine in the fine-tuning stage. However, I often get the error message mentioned above when I deploy my model with Langchain.
> 
> \### System Info
> 
> System Information
> \------------------
> \> OS: Linux
> \> OS Version: #49~22.04.1-Ubuntu SMP PREEMPT\_DYNAMIC Wed Nov 6 17:42:15 UTC 2
> \> Python Version: 3.8.19 (default, Mar 20 2024, 19:58:24) 
> \[GCC 11.2.0\]
> 
> Package Information
> \-------------------
> \> langchain\_core: 0.2.41
> \> langchain: 0.2.16
> \> langchain\_community: 0.2.17
> \> langsmith: 0.1.132
> \> langchain\_chroma: 0.1.4
> \> langchain\_groq: 0.1.10
> \> langchain\_huggingface: 0.0.3
> \> langchain\_openai: 0.1.25
> \> langchain\_text\_splitters: 0.2.4
> \> langserve: 0.2.3
> 
> Optional packages not installed
> \-------------------------------
> \> langgraph
> 
> Other Dependencies
> \------------------
> \> aiohttp: 3.10.9
> \> async-timeout: 4.0.3
> \> chromadb: 0.5.11
> \> dataclasses-json: 0.6.7
> \> fastapi: 0.115.0
> \> groq: 0.11.0
> \> httpx: 0.27.2
> \> huggingface-hub: 0.25.1
> \> jsonpatch: 1.33
> \> numpy: 1.24.3
> \> openai: 1.51.1
> \> orjson: 3.10.7
> \> packaging: 24.0
> \> pydantic: 2.9.2
> \> pyproject-toml: 0.0.10
> \> PyYAML: 6.0.1
> \> requests: 2.32.3
> \> requests-toolbelt: 1.0.0
> \> sentence-transformers: 3.1.1
> \> SQLAlchemy: 2.0.35
> \> sse-starlette: 2.1.3
> \> tenacity: 8.5.0
> \> tiktoken: 0.7.0
> \> tokenizers: 0.20.0
> \> transformers: 4.46.3
> \> typing-extensions: 4.11.0

> <https://github.com/huggingface/transformers/issues/30063>
>
> \### System Info
> \`\`\`
> Package Version
> \--------------------…-------- ------------
> absl-py 1.4.0
> accelerate 0.21.0
> aiohttp 3.8.4
> aiosignal 1.3.1
> aliyun-python-sdk-core 2.13.36
> aliyun-python-sdk-kms 2.16.1
> annotated-types 0.6.0
> antlr4-python3-runtime 4.9.3
> anyio 3.7.1
> apphub 1.0.0
> argon2-cffi 21.3.0
> argon2-cffi-bindings 21.2.0
> arrow 1.2.3
> asttokens 2.2.1
> astunparse 1.6.3
> async-timeout 4.0.2
> attrs 23.1.0
> Babel 2.12.1
> backcall 0.2.0
> beautifulsoup4 4.12.2
> bitsandbytes 0.40.2
> bleach 6.0.0
> blessed 1.20.0
> boltons 23.0.0
> brotlipy 0.7.0
> cachetools 5.3.1
> certifi 2023.7.22
> cffi 1.15.1
> chardet 3.0.4
> charset-normalizer 2.0.4
> click 7.1.2
> cmake 3.25.0
> comm 0.1.4
> conda 23.7.2
> conda-content-trust 0.1.3
> conda-libmamba-solver 23.5.0
> conda-package-handling 2.1.0
> conda\_package\_streaming 0.8.0
> contourpy 1.2.0
> crcmod 1.7
> croniter 1.3.15
> cryptography 39.0.1
> cycler 0.12.1
> dateutils 0.6.12
> debugpy 1.6.7
> decorator 5.1.1
> deepdiff 6.3.1
> defusedxml 0.7.1
> diffusers 0.18.2
> ecdsa 0.18.0
> exceptiongroup 1.1.2
> executing 1.2.0
> fastapi 0.88.0
> fastjsonschema 2.18.0
> featurize 0.0.24
> filelock 3.9.0
> flatbuffers 23.5.26
> fonttools 4.44.0
> frozenlist 1.4.0
> fsspec 2024.3.1
> gast 0.4.0
> google-auth 2.22.0
> google-auth-oauthlib 1.0.0
> google-pasta 0.2.0
> grpcio 1.56.0
> gunicorn 21.2.0
> h11 0.14.0
> h5py 3.9.0
> httpcore 0.17.3
> httptools 0.6.1
> httpx 0.24.1
> huggingface-hub 0.22.2
> idna 2.10
> imageio 2.31.1
> imageio-ffmpeg 0.4.8
> importlib-metadata 6.8.0
> inquirer 3.1.3
> install 1.3.5
> ipykernel 6.25.0
> ipython 8.14.0
> ipython-genutils 0.2.0
> itsdangerous 2.1.2
> jaxtyping 0.2.20
> jedi 0.19.0
> Jinja2 3.1.2
> jmespath 0.10.0
> joblib 1.3.2
> json5 0.9.14
> jsonpatch 1.32
> jsonpointer 2.1
> jsonschema 4.18.6
> jsonschema-specifications 2023.7.1
> jupyter\_client 8.3.0
> jupyter\_core 5.3.1
> jupyter-server 1.24.0
> jupyterlab 3.2.9
> jupyterlab-pygments 0.2.2
> jupyterlab\_server 2.24.0
> keras 2.13.1
> kiwisolver 1.4.5
> lazy\_loader 0.3
> libclang 16.0.6
> libigl 2.4.1
> libmambapy 1.4.1
> lightning 2.0.0
> lightning-cloud 0.5.37
> lightning-utilities 0.9.0
> lit 15.0.7
> Markdown 3.4.3
> MarkupSafe 2.1.2
> matplotlib 3.7.2
> matplotlib-inline 0.1.6
> mdurl 0.1.2
> mistune 3.0.1
> mpmath 1.2.1
> multidict 6.0.4
> nbclassic 0.2.8
> nbclient 0.8.0
> nbconvert 7.7.3
> nbformat 5.9.2
> nerfacc 0.5.2
> nest-asyncio 1.5.7
> networkx 3.0
> ninja 1.11.1
> notebook 6.4.12
> numpy 1.24.1
> nvdiffrast 0.3.1
> oauthlib 3.2.2
> omegaconf 2.3.0
> opencv-python 4.8.1.78
> opt-einsum 3.3.0
> ordered-set 4.1.0
> oss2 2.18.1
> packaging 23.0
> pandas 2.1.2
> pandocfilters 1.5.0
> parso 0.8.3
> peft 0.10.0
> pexpect 4.8.0
> pickleshare 0.7.5
> Pillow 9.3.0
> pip 23.1.2
> platformdirs 3.10.0
> pluggy 1.0.0
> prometheus-client 0.17.1
> prompt-toolkit 3.0.39
> protobuf 4.23.4
> psutil 5.9.5
> ptyprocess 0.7.0
> pure-eval 0.2.2
> pyasn1 0.5.0
> pyasn1-modules 0.3.0
> pycosat 0.6.4
> pycparser 2.21
> pycryptodome 3.18.0
> pydantic 1.10.11
> pydantic\_core 2.10.1
> Pygments 2.15.1
> PyJWT 2.8.0
> pyOpenSSL 23.0.0
> pyparsing 3.0.9
> PySocks 1.7.1
> python-dateutil 2.8.2
> python-dotenv 1.0.0
> python-editor 1.0.4
> pytorch-lightning 2.0.5
> pytz 2023.3.post1
> PyYAML 6.0.1
> pyzmq 25.1.0
> readchar 4.0.5
> referencing 0.30.0
> regex 2023.12.25
> requests 2.31.0
> requests-oauthlib 1.3.1
> rich 13.4.2
> rpds-py 0.9.2
> rsa 4.9
> ruamel.yaml 0.17.21
> ruamel.yaml.clib 0.2.6
> safetensors 0.4.2
> scikit-image 0.22.0
> scikit-learn 1.3.2
> scipy 1.11.3
> seaborn 0.13.0
> Send2Trash 1.8.2
> sentencepiece 0.1.99
> setuptools 67.8.0
> six 1.16.0
> sniffio 1.3.0
> socksio 1.0.0
> soupsieve 2.4.1
> sshpubkeys 3.3.1
> stack-data 0.6.2
> starlette 0.22.0
> starsessions 1.3.0
> sympy 1.11.1
> tabulate 0.8.7
> tensorboard 2.13.0
> tensorboard-data-server 0.7.1
> tensorflow 2.13.0
> tensorflow-estimator 2.13.0
> tensorflow-io-gcs-filesystem 0.33.0
> termcolor 2.3.0
> terminado 0.17.1
> threadpoolctl 3.2.0
> tifffile 2023.9.26
> tinycss2 1.2.1
> tokenizers 0.15.2
> toolz 0.12.0
> torch 2.0.1+cu118
> torchaudio 2.0.2+cu118
> torchmetrics 1.0.1
> torchvision 0.15.2+cu118
> tornado 6.3.2
> tqdm 4.65.0
> traitlets 5.9.0
> transformers 4.39.3
> trimesh 3.22.4
> triton 2.0.0
> typing\_extensions 4.8.0
> tzdata 2023.3
> urllib3 1.25.11
> uvicorn 0.23.1
> uvloop 0.19.0
> watchfiles 0.21.0
> wcwidth 0.2.6
> webencodings 0.5.1
> websocket-client 1.2.1
> websockets 11.0.3
> Werkzeug 2.3.6
> wheel 0.38.4
> workspace 0.1.0
> wrapt 1.15.0
> xatlas 0.0.7
> yarl 1.9.2
> zstandard 0.19.0
> \`\`\`
> \### Who can help?
> 
> @younesbelkada @ArthurZucker
> 
> \### Information
> 
> \- \[\] The official example scripts
> \- \[X\] My own modified scripts
> 
> \### Tasks
> 
> \- \[\] An officially supported task in the \`examples\` folder (such as GLUE/SQuAD, ...)
> \- \[\] My own task or dataset (give details below)
> 
> \### Reproduction
> \`\`\`python 
> from transformers import AutoTokenizer, AutoModel, AutoModelForCausalLM
> from peft import get\_peft\_model, LoraConfig, TaskType, PeftModel
> from dataclasses import dataclass, field
> from typing import List, Optional, Tuple, Union
> 
> import torch
> import torch.nn as nn
> 
> 
> 
> model = AutoModelForCausalLM.from\_pretrained(
> 'mistralai/Mistral-7B-Instruct-v0.2',
> trust\_remote\_code= True,
> device\_map='auto',
> force\_download=True, 
> resume\_download= False,
> 
> )
> 
> model = model.to('cuda')
> \`\`\`
> \### Expected behavior
> 
> Model loading success

---

<div class="post-metadata">

**Author:** ![hawkiyc](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/hawkiyc/32/33085_2.png) [@hawkiyc](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2Fhawkiyc)%5C
**Post date:** [February 28, 2025, 6:25pm UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fcannot-copy-out-of-meta-tensor-no-data%2F128996%2F5 "2025-02-28T18:25:36Z")

</div>

The weirder thing is that I can deploy my model while initiating my app with the streamlet run command. Yet, this error pops up after several conversations.
