Run this model with HF Jobs
Run nikravan/glm-4vq on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/nikravan/glm-4vq. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/nikravan/glm-4vq on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use nikravan/glm-4vq with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use nikravan/glm-4vq with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("document-question-answering", model="nikravan/glm-4vq", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("nikravan/glm-4vq", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
ChatGLM4Tokenizer._pad() got an unexpected keyword argument 'padding_side'
I've downloaded the offline model from git and try it ,I don't known why but something goes wrong.
It looks like a version update(cuda or pytorch?) causing some method failed. But I don't know how to fix it
Thanks for your help.
If you need more information, please let me know :)
Here is cuda and torch version.
>>> import torch
>>> print(torch.__version__)
2.5.1
>>> print(torch.version.cuda)
12.4
Here is my pip requirement . Windows11_x86
accelerate @ file:///H:/Models/accelerate
aiofiles==23.2.1
aiohappyeyeballs @ file:///home/conda/feedstock_root/build_artifacts/aiohappyeyeballs_1733331917983/work
aiohttp @ file:///D:/bld/aiohttp_1733124742430/work
aiosignal @ file:///home/conda/feedstock_root/build_artifacts/aiosignal_1733332106743/work
annotated-types==0.7.0
anyio @ file:///home/conda/feedstock_root/build_artifacts/anyio_1728935693959/work
argon2-cffi @ file:///home/conda/feedstock_root/build_artifacts/argon2-cffi_1733311059102/work
argon2-cffi-bindings @ file:///D:/bld/argon2-cffi-bindings_1725356679565/work
arrow @ file:///home/conda/feedstock_root/build_artifacts/arrow_1696128962909/work
asttokens @ file:///home/conda/feedstock_root/build_artifacts/asttokens_1733250440834/work
async-lru @ file:///home/conda/feedstock_root/build_artifacts/async-lru_1690563019058/work
async-timeout @ file:///home/conda/feedstock_root/build_artifacts/async-timeout_1733235340728/work
attrs @ file:///home/conda/feedstock_root/build_artifacts/attrs_1722977137225/work
babel @ file:///home/conda/feedstock_root/build_artifacts/babel_1733236348445/work
beautifulsoup4 @ file:///home/conda/feedstock_root/build_artifacts/beautifulsoup4_1733230845337/work
bitsandbytes==0.45.0
bleach @ file:///home/conda/feedstock_root/build_artifacts/bleach_1733302318120/work
Brotli @ file:///D:/bld/brotli-split_1725267609074/work
cached-property @ file:///home/conda/feedstock_root/build_artifacts/cached_property_1615209429212/work
certifi @ file:///home/conda/feedstock_root/build_artifacts/certifi_1725278078093/work/certifi
cffi @ file:///D:/bld/cffi_1725560649097/work
charset-normalizer @ file:///home/conda/feedstock_root/build_artifacts/charset-normalizer_1733218092148/work
click==8.1.7
colorama @ file:///home/conda/feedstock_root/build_artifacts/colorama_1733218098505/work
comm @ file:///home/conda/feedstock_root/build_artifacts/comm_1710320294760/work
datasets @ file:///home/conda/feedstock_root/build_artifacts/datasets_1731706630038/work
debugpy @ file:///D:/bld/debugpy_1732236678331/work
decorator @ file:///home/conda/feedstock_root/build_artifacts/decorator_1733236420667/work
defusedxml @ file:///home/conda/feedstock_root/build_artifacts/defusedxml_1615232257335/work
dill @ file:///home/conda/feedstock_root/build_artifacts/dill_1706434688412/work
entrypoints @ file:///home/conda/feedstock_root/build_artifacts/entrypoints_1733327148154/work
exceptiongroup @ file:///home/conda/feedstock_root/build_artifacts/exceptiongroup_1733208806608/work
executing @ file:///home/conda/feedstock_root/build_artifacts/executing_1725214404607/work
fastapi==0.115.6
fastjsonschema @ file:///home/conda/feedstock_root/build_artifacts/python-fastjsonschema_1733235979760/work/dist
ffmpy==0.4.0
filelock @ file:///home/conda/feedstock_root/build_artifacts/filelock_1733240801289/work
fqdn @ file:///home/conda/feedstock_root/build_artifacts/fqdn_1733327382592/work/dist
frozenlist @ file:///D:/bld/frozenlist_1729699474736/work
fsspec==2024.10.0
gradio==5.8.0
gradio_client==1.5.1
h11 @ file:///home/conda/feedstock_root/build_artifacts/h11_1733327467879/work
h2 @ file:///home/conda/feedstock_root/build_artifacts/h2_1733298745555/work
hpack @ file:///home/conda/feedstock_root/build_artifacts/hpack_1733299205993/work
httpcore @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_httpcore_1731707562/work
httpx @ file:///home/conda/feedstock_root/build_artifacts/httpx_1732830951013/work
huggingface_hub @ file:///home/conda/feedstock_root/build_artifacts/huggingface_hub_1733170165635/work
hyperframe @ file:///home/conda/feedstock_root/build_artifacts/hyperframe_1733298771451/work
idna @ file:///home/conda/feedstock_root/build_artifacts/idna_1733211830134/work
importlib_metadata @ file:///home/conda/feedstock_root/build_artifacts/importlib-metadata_1733223117029/work
importlib_resources @ file:///home/conda/feedstock_root/build_artifacts/importlib_resources_1733231327252/work
ipykernel @ file:///D:/bld/ipykernel_1719845595208/work
ipython @ file:///D:/bld/ipython_1732896960890/work
isoduration @ file:///home/conda/feedstock_root/build_artifacts/isoduration_1638811571363/work/dist
jedi @ file:///home/conda/feedstock_root/build_artifacts/jedi_1733300866624/work
Jinja2 @ file:///home/conda/feedstock_root/build_artifacts/jinja2_1733217336947/work
json5 @ file:///home/conda/feedstock_root/build_artifacts/json5_1733272076743/work
jsonpointer @ file:///D:/bld/jsonpointer_1725302958210/work
jsonschema @ file:///home/conda/feedstock_root/build_artifacts/jsonschema_1733472696581/work
jsonschema-specifications @ file:///tmp/tmpvslgxhz5/src
jupyter-events @ file:///home/conda/feedstock_root/build_artifacts/jupyter_events_1733441322938/work
jupyter-lsp @ file:///home/conda/feedstock_root/build_artifacts/jupyter-lsp-meta_1712707420468/work/jupyter-lsp
jupyter_client @ file:///home/conda/feedstock_root/build_artifacts/jupyter_client_1733440914442/work
jupyter_core @ file:///D:/bld/jupyter_core_1727163532151/work
jupyter_server @ file:///home/conda/feedstock_root/build_artifacts/jupyter_server_1733428613680/work
jupyter_server_terminals @ file:///home/conda/feedstock_root/build_artifacts/jupyter_server_terminals_1733427956852/work
jupyterlab @ file:///home/conda/feedstock_root/build_artifacts/jupyterlab_1733261003191/work
jupyterlab_pygments @ file:///home/conda/feedstock_root/build_artifacts/jupyterlab_pygments_1733328101776/work
jupyterlab_server @ file:///home/conda/feedstock_root/build_artifacts/jupyterlab_server-split_1721163288448/work
lxml==5.3.0
markdown-it-py==3.0.0
MarkupSafe==2.1.5
matplotlib-inline @ file:///home/conda/feedstock_root/build_artifacts/matplotlib-inline_1733416936468/work
mdurl==0.1.2
mistune @ file:///home/conda/feedstock_root/build_artifacts/mistune_1733258715622/work
mpmath @ file:///home/conda/feedstock_root/build_artifacts/mpmath_1733302684489/work
multidict @ file:///D:/bld/multidict_1729065633457/work
multiprocess @ file:///D:/bld/multiprocess_1724954696823/work
nbclient @ file:///home/conda/feedstock_root/build_artifacts/nbclient_1732882344310/work
nbconvert @ file:///home/conda/feedstock_root/build_artifacts/nbconvert-meta_1733405477194/work
nbformat @ file:///home/conda/feedstock_root/build_artifacts/nbformat_1733402752141/work
nest_asyncio @ file:///home/conda/feedstock_root/build_artifacts/nest-asyncio_1733325553580/work
networkx @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_networkx_1731521053/work
notebook @ file:///home/conda/feedstock_root/build_artifacts/notebook_1733367085854/work
notebook_shim @ file:///home/conda/feedstock_root/build_artifacts/notebook-shim_1733408315203/work
numpy @ file:///D:/bld/numpy_1730588038333/work/dist/numpy-2.1.3-cp310-cp310-win_amd64.whl#sha256=c29fd581b8df1c3329e6d95e58bdf9db58b0a6a4d713088f166cf377062400db
orjson==3.10.12
overrides @ file:///home/conda/feedstock_root/build_artifacts/overrides_1706394519472/work
packaging @ file:///home/conda/feedstock_root/build_artifacts/packaging_1733203243479/work
pandas @ file:///D:/bld/pandas_1726878561601/work
pandocfilters @ file:///home/conda/feedstock_root/build_artifacts/pandocfilters_1631603243851/work
parso @ file:///home/conda/feedstock_root/build_artifacts/parso_1733271261340/work
pickleshare @ file:///home/conda/feedstock_root/build_artifacts/pickleshare_1733327343728/work
pillow @ file:///D:/bld/pillow_1726075253811/work
pkgutil_resolve_name @ file:///home/conda/feedstock_root/build_artifacts/pkgutil-resolve-name_1733344503739/work
platformdirs @ file:///home/conda/feedstock_root/build_artifacts/platformdirs_1733232627818/work
prometheus_client @ file:///home/conda/feedstock_root/build_artifacts/prometheus_client_1733327310477/work
prompt_toolkit @ file:///home/conda/feedstock_root/build_artifacts/prompt-toolkit_1733302527033/work
propcache @ file:///D:/bld/propcache_1733391844283/work
psutil==5.9.8
pure_eval @ file:///home/conda/feedstock_root/build_artifacts/pure_eval_1721585709575/work
pyarrow==18.1.0
pycparser @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_pycparser_1733195786/work
pydantic==2.10.3
pydantic_core==2.27.1
pydub==0.25.1
Pygments @ file:///home/conda/feedstock_root/build_artifacts/pygments_1733221634316/work
PyMuPDF==1.25.0
PySocks @ file:///D:/bld/pysocks_1733217287171/work
python-dateutil @ file:///home/conda/feedstock_root/build_artifacts/python-dateutil_1733215673016/work
python-docx==1.1.2
python-json-logger @ file:///home/conda/feedstock_root/build_artifacts/python-json-logger_1677079630776/work
python-multipart==0.0.19
python-pptx==1.0.2
pytz @ file:///home/conda/feedstock_root/build_artifacts/pytz_1706886791323/work
pywin32==307
pywinpty @ file:///D:/bld/pywinpty_1729201112717/work/target/wheels/pywinpty-2.0.14-cp310-none-win_amd64.whl#sha256=47cfa77d7fb3a732a342cff241421e63be66ae1f11237e46a8ef5a2533ace3b5
PyYAML @ file:///D:/bld/pyyaml_1725456311802/work
pyzmq @ file:///D:/bld/pyzmq_1728642398422/work
referencing @ file:///home/conda/feedstock_root/build_artifacts/referencing_1733366743674/work
regex @ file:///D:/bld/regex_1730952192742/work
requests @ file:///home/conda/feedstock_root/build_artifacts/requests_1733217035951/work
rfc3339-validator @ file:///home/conda/feedstock_root/build_artifacts/rfc3339-validator_1638811747357/work
rfc3986-validator @ file:///home/conda/feedstock_root/build_artifacts/rfc3986-validator_1598024191506/work
rich==13.9.4
rpds-py @ file:///D:/bld/rpds-py_1733366638678/work
ruff==0.8.2
safehttpx==0.1.6
safetensors @ file:///D:/bld/safetensors_1725632190593/work
semantic-version==2.10.0
Send2Trash @ file:///D:/bld/send2trash_1733322089150/work
shellingham==1.5.4
six @ file:///home/conda/feedstock_root/build_artifacts/six_1733380938961/work
sniffio @ file:///home/conda/feedstock_root/build_artifacts/sniffio_1733244044561/work
soupsieve @ file:///home/conda/feedstock_root/build_artifacts/soupsieve_1693929250441/work
spaces==0.30.4
stack-data @ file:///home/conda/feedstock_root/build_artifacts/stack_data_1669632077133/work
starlette==0.41.3
sympy==1.13.1
terminado @ file:///D:/bld/terminado_1710262761616/work
tiktoken==0.8.0
tinycss2 @ file:///home/conda/feedstock_root/build_artifacts/tinycss2_1729802851396/work
tokenizers @ file:///D:/bld/tokenizers_1732657721701/work/bindings/python
tomli @ file:///home/conda/feedstock_root/build_artifacts/tomli_1733256695513/work
tomlkit==0.13.2
torch==2.5.1
torchaudio==2.5.1
torchvision==0.20.1
tornado @ file:///D:/bld/tornado_1732615925919/work
tqdm @ file:///home/conda/feedstock_root/build_artifacts/tqdm_1732497199771/work
traitlets @ file:///home/conda/feedstock_root/build_artifacts/traitlets_1733367359838/work
transformers @ file:///home/conda/feedstock_root/build_artifacts/transformers_1731981253858/work
typer==0.15.1
types-python-dateutil @ file:///home/conda/feedstock_root/build_artifacts/types-python-dateutil_1733279635066/work
typing_extensions @ file:///home/conda/feedstock_root/build_artifacts/typing_extensions_1733188668063/work
typing_utils @ file:///home/conda/feedstock_root/build_artifacts/typing_utils_1733331286120/work
tzdata @ file:///home/conda/feedstock_root/build_artifacts/python-tzdata_1733235305708/work
uri-template @ file:///home/conda/feedstock_root/build_artifacts/uri-template_1733323593477/work/dist
urllib3 @ file:///home/conda/feedstock_root/build_artifacts/urllib3_1733206856906/work
uvicorn==0.32.1
wcwidth @ file:///home/conda/feedstock_root/build_artifacts/wcwidth_1733231326287/work
webcolors @ file:///home/conda/feedstock_root/build_artifacts/webcolors_1733359735138/work
webencodings @ file:///home/conda/feedstock_root/build_artifacts/webencodings_1733236011802/work
websocket-client @ file:///home/conda/feedstock_root/build_artifacts/websocket-client_1733157342724/work
websockets==14.1
win_inet_pton @ file:///D:/bld/win_inet_pton_1733130564612/work
XlsxWriter==3.2.0
xxhash @ file:///D:/bld/python-xxhash_1725272218615/work
yarl @ file:///D:/bld/yarl_1733428802263/work
zipp @ file:///home/conda/feedstock_root/build_artifacts/zipp_1732827521216/work
zstandard==0.23.0
Here is python file. Modified from jupyter
import torch
from PIL import Image
import gradio as gr
import spaces
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
import os
from threading import Thread
import pymupdf
import docx
from pptx import Presentation
MODEL_LIST = ["nikravan/glm-4vq"]
HF_TOKEN = os.environ.get("HF_TOKEN", None)
MODEL_ID = MODEL_LIST[0]
MODEL_NAME = "GLM-4vq"
TITLE = "<h1>3ML-bot</h1>"
DESCRIPTION = f"""
<center>
<p>😊 A MultiModal MultiLingual(MMML) Chat.
<br>
🚀 MODEL NOW: <a href="https://hf.co/{MODEL_ID}">{MODEL_NAME}</a>
</center>"""
CSS = """
h1 {
text-align: center;
display: block;
}
"""
# model = AutoModelForCausalLM.from_pretrained(
# MODEL_ID,
# torch_dtype=torch.bfloat16,
# low_cpu_mem_usage=True,
# trust_remote_code=True
# )
model = AutoModelForCausalLM.from_pretrained(
"H:/Models/glm-4vq",
torch_dtype=torch.bfloat16,
low_cpu_mem_usage=True,
trust_remote_code=True
)
tokenizer = AutoTokenizer.from_pretrained("H:/Models/glm-4vq", trust_remote_code=True)
# tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
model.eval()
def extract_text(path):
return open(path, 'r').read()
def extract_pdf(path):
doc = pymupdf.open(path)
text = ""
for page in doc:
text += page.get_text()
return text
def extract_docx(path):
doc = docx.Document(path)
data = []
for paragraph in doc.paragraphs:
data.append(paragraph.text)
content = '\n\n'.join(data)
return content
def extract_pptx(path):
prs = Presentation(path)
text = ""
for slide in prs.slides:
for shape in slide.shapes:
if hasattr(shape, "text"):
text += shape.text + "\n"
return text
def mode_load(path):
choice = ""
file_type = path.split(".")[-1]
print(file_type)
if file_type in ["pdf", "txt", "py", "docx", "pptx", "json", "cpp", "md"]:
if file_type.endswith("pdf"):
content = extract_pdf(path)
elif file_type.endswith("docx"):
content = extract_docx(path)
elif file_type.endswith("pptx"):
content = extract_pptx(path)
else:
content = extract_text(path)
choice = "doc"
print(content[:100])
return choice, content[:5000]
elif file_type in ["png", "jpg", "jpeg", "bmp", "tiff", "webp"]:
content = Image.open(path).convert('RGB')
choice = "image"
return choice, content
else:
raise gr.Error("Oops, unsupported files.")
@spaces.GPU()
def stream_chat(message, history: list, temperature: float, max_length: int, top_p: float, top_k: int, penalty: float):
print(f'message is - {message}')
print(f'history is - {history}')
conversation = []
prompt_files = []
if message["files"]:
choice, contents = mode_load(message["files"][-1])
if choice == "image":
conversation.append({"role": "user", "image": contents, "content": message['text']})
elif choice == "doc":
format_msg = contents + "\n\n\n" + "{} files uploaded.\n" + message['text']
conversation.append({"role": "user", "content": format_msg})
else:
if len(history) == 0:
# raise gr.Error("Please upload an image first.")
contents = None
conversation.append({"role": "user", "content": message['text']})
else:
# image = Image.open(history[0][0][0])
for prompt, answer in history:
if answer is None:
prompt_files.append(prompt[0])
conversation.extend([{"role": "user", "content": ""}, {"role": "assistant", "content": ""}])
else:
conversation.extend([{"role": "user", "content": prompt}, {"role": "assistant", "content": answer}])
if len(prompt_files) > 0:
choice, contents = mode_load(prompt_files[-1])
else:
choice = ""
conversation.append({"role": "user", "image": "", "content": message['text']})
if choice == "image":
conversation.append({"role": "user", "image": contents, "content": message['text']})
elif choice == "doc":
format_msg = contents + "\n\n\n" + "{} files uploaded.\n" + message['text']
conversation.append({"role": "user", "content": format_msg})
print(f"Conversation is -\n{conversation}")
# input_ids = tokenizer.apply_chat_template(conversation, tokenize=True, add_generation_prompt=True,
# return_tensors="pt", return_dict=True).to(model.device)
input_ids = tokenizer.apply_chat_template(
conversation,
tokenize=True,
add_generation_prompt=True,
return_tensors="pt",
return_dict=True
).to(model.device)
streamer = TextIteratorStreamer(tokenizer, timeout=60.0, skip_prompt=True, skip_special_tokens=True)
generate_kwargs = dict(
max_length=max_length,
streamer=streamer,
do_sample=True,
top_p=top_p,
top_k=top_k,
temperature=temperature,
repetition_penalty=penalty,
eos_token_id=[151329, 151336, 151338],
)
gen_kwargs = {**input_ids, **generate_kwargs}
with torch.no_grad():
thread = Thread(target=model.generate, kwargs=gen_kwargs)
thread.start()
buffer = ""
for new_text in streamer:
buffer += new_text
yield buffer
chatbot = gr.Chatbot(type='messages'
# rtl=True
)
chat_input = gr.MultimodalTextbox(
interactive=True,
placeholder="Enter message or upload a file ...",
show_label=False,
# rtl=True,
)
EXAMPLES = [
[{"text": "Write a poem about spring season in French Language", }],
[{"text": "what does this chart mean?", "files": ["sales.png"]}],
[{"text": "¿Qué está escrito a mano en esta foto?", "files": ["receipt1.png"]}],
[{"text": "در مورد این عکس توضیح بده و بگو این چه فصلی می تواند باشد", "files": ["nature.jpg"]}]
]
with gr.Blocks(css=CSS, theme="soft", fill_height=True) as demo:
gr.HTML(TITLE)
gr.HTML(DESCRIPTION)
gr.ChatInterface(
fn=stream_chat,
multimodal=True,
textbox=chat_input,
chatbot=chatbot,
fill_height=True,
additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),
additional_inputs=[
gr.Slider(
minimum=0,
maximum=1,
step=0.1,
value=0.8,
label="Temperature",
render=False,
),
gr.Slider(
minimum=1024,
maximum=8192,
step=1,
value=4096,
label="Max Length",
render=False,
),
gr.Slider(
minimum=0.0,
maximum=1.0,
step=0.1,
value=1.0,
label="top_p",
render=False,
),
gr.Slider(
minimum=1,
maximum=20,
step=1,
value=10,
label="top_k",
render=False,
),
gr.Slider(
minimum=0.0,
maximum=2.0,
step=0.1,
value=1.0,
label="Repetition penalty",
render=False,
),
],
),
gr.Examples(EXAMPLES, [chat_input])
if __name__ == "__main__":
demo.queue(api_open=False).launch(show_api=False, share=True)
Here is error info
Unused kwargs: ['_load_in_4bit', '_load_in_8bit', 'quant_method']. These kwargs are not used in <class 'transformers.utils.quantization_config.BitsAndBytesConfig'>.
Loading checkpoint shards: 100%|██████████| 5/5 [00:05<00:00, 1.04s/it]
E:\mambaForge\envs\3ML\lib\site-packages\gradio\chat_interface.py:226: UserWarning: The gr.ChatInterface was not provided with a type, so the type of the gr.Chatbot, 'messages', will be used.
warnings.warn(
* Running on local URL: http://127.0.0.1:7860
Could not create share link. Missing file: E:\mambaForge\envs\3ML\lib\site-packages\gradio\frpc_windows_amd64_v0.3.
Please check your internet connection. This can happen if your antivirus software blocks the download of this file. You can install manually by following these steps:
1. Download this file: https://cdn-media.huggingface.co/frpc-gradio-0.3/frpc_windows_amd64.exe
2. Rename the downloaded file to: frpc_windows_amd64_v0.3
3. Move the file to this location: E:\mambaForge\envs\3ML\lib\site-packages\gradio
message is - {'text': 'what does this chart mean?', 'files': ['C:\\Users\\User\\AppData\\Local\\Temp\\gradio\\a44c03f6f954296f210013c49d11565b6ca30745443f179699e8138841777ef0\\sales.png']}
history is - []
png
Conversation is -
[{'role': 'user', 'image': <PIL.Image.Image image mode=RGB size=1758x888 at 0x1D0CD8B78E0>, 'content': 'what does this chart mean?'}]
Traceback (most recent call last):
File "E:\mambaForge\envs\3ML\lib\site-packages\gradio\queueing.py", line 624, in process_events
response = await route_utils.call_process_api(
File "E:\mambaForge\envs\3ML\lib\site-packages\gradio\route_utils.py", line 323, in call_process_api
output = await app.get_blocks().process_api(
File "E:\mambaForge\envs\3ML\lib\site-packages\gradio\blocks.py", line 2043, in process_api
result = await self.call_function(
File "E:\mambaForge\envs\3ML\lib\site-packages\gradio\blocks.py", line 1602, in call_function
prediction = await utils.async_iteration(iterator)
File "E:\mambaForge\envs\3ML\lib\site-packages\gradio\utils.py", line 710, in async_iteration
return await anext(iterator)
File "E:\mambaForge\envs\3ML\lib\site-packages\gradio\utils.py", line 815, in asyncgen_wrapper
response = await iterator.__anext__()
File "E:\mambaForge\envs\3ML\lib\site-packages\gradio\chat_interface.py", line 727, in _stream_fn
first_response = await utils.async_iteration(generator)
File "E:\mambaForge\envs\3ML\lib\site-packages\gradio\utils.py", line 710, in async_iteration
return await anext(iterator)
File "E:\mambaForge\envs\3ML\lib\site-packages\gradio\utils.py", line 704, in __anext__
return await anyio.to_thread.run_sync(
File "E:\mambaForge\envs\3ML\lib\site-packages\anyio\to_thread.py", line 56, in run_sync
return await get_async_backend().run_sync_in_worker_thread(
File "E:\mambaForge\envs\3ML\lib\site-packages\anyio\_backends\_asyncio.py", line 2441, in run_sync_in_worker_thread
return await future
File "E:\mambaForge\envs\3ML\lib\asyncio\futures.py", line 285, in __await__
yield self # This tells Task to wait for completion.
File "E:\mambaForge\envs\3ML\lib\asyncio\tasks.py", line 304, in __wakeup
future.result()
File "E:\mambaForge\envs\3ML\lib\asyncio\futures.py", line 201, in result
raise self._exception.with_traceback(self._exception_tb)
File "E:\mambaForge\envs\3ML\lib\site-packages\anyio\_backends\_asyncio.py", line 943, in run
result = context.run(func, *args)
File "E:\mambaForge\envs\3ML\lib\site-packages\gradio\utils.py", line 687, in run_sync_iterator_async
return next(iterator)
File "F:\EndGraduated\3ML\run.py", line 151, in stream_chat
input_ids = tokenizer.apply_chat_template(
File "C:\Users\QLozin\.cache\huggingface\modules\transformers_modules\glm-4vq\tokenization_chatglm.py", line 251, in apply_chat_template
output = self.batch_encode_plus(
File "E:\mambaForge\envs\3ML\lib\site-packages\transformers\tokenization_utils_base.py", line 3311, in batch_encode_plus
return self._batch_encode_plus(
File "E:\mambaForge\envs\3ML\lib\site-packages\transformers\tokenization_utils.py", line 892, in _batch_encode_plus
batch_outputs = self._batch_prepare_for_model(
File "E:\mambaForge\envs\3ML\lib\site-packages\transformers\tokenization_utils.py", line 970, in _batch_prepare_for_model
batch_outputs = self.pad(
File "E:\mambaForge\envs\3ML\lib\site-packages\transformers\tokenization_utils_base.py", line 3527, in pad
outputs = self._pad(
TypeError: ChatGLM4Tokenizer._pad() got an unexpected keyword argument 'padding_side'
Quote:
https://github.com/THUDM/GLM-4/issues/263
https://huggingface.co/THUDM/LongWriter-glm4-9b/commit/778b5712634889f5123d6c463ca383bc6dd5c621#d2h-069285
https://github.com/THUDM/ChatGLM3/issues/1324
https://github.com/THUDM/GLM-4/issues/439
Main dependent version
conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia
pip install PyMuPDF python-docx python-pptx tiktoken gradio spaces bitsandbytes transformers tokenizers accelerate \
"transformers<=4.40" "tokenizers<=0.19.1" "gradio<=4.37.2" "accelerate<=0.31.0" "gradio-client<=1.0.2" "spaces<=0.28.3"
Quick start work , jupyter programme doesn't .
Error Info
File "/home/ubuntu/miniforge3/envs/3ml/lib/python3.10/site-packages/gradio/component_meta.py", line 163, in wrapper
return fn(self, **kwargs)
TypeError: Chatbot.__init__() got an unexpected keyword argument 'type'
1
This pip package version work well.
The most important dependence include cuda, torch, transformer, gradio , spaces,accelerate, tokenizers, fastapi. (some dep listed above)
accelerate 0.31.0
aiofiles 23.2.1
altair 5.5.0
annotated-types 0.7.0
anyio 4.7.0
attrs 24.2.0
bitsandbytes 0.45.0
Brotli 1.1.0
certifi 2024.8.30
cffi 1.17.1
charset-normalizer 3.4.0
click 8.1.7
contourpy 1.3.1
cycler 0.12.1
exceptiongroup 1.2.2
fastapi 0.112.4
ffmpy 0.4.0
filelock 3.16.1
fonttools 4.55.2
fsspec 2024.10.0
gmpy2 2.1.5
gradio 4.37.2
gradio_client 1.0.2
h11 0.14.0
h2 4.1.0
hpack 4.0.0
httpcore 1.0.7
httpx 0.28.1
huggingface-hub 0.26.5
hyperframe 6.0.1
idna 3.10
importlib_resources 6.4.5
Jinja2 3.1.4
jsonschema 4.23.0
jsonschema-specifications 2024.10.1
kiwisolver 1.4.7
lxml 5.3.0
markdown-it-py 3.0.0
MarkupSafe 2.1.5
matplotlib 3.9.3
mdurl 0.1.2
mpmath 1.3.0
narwhals 1.16.0
networkx 3.4.2
numpy 1.26.4
orjson 3.10.12
packaging 24.2
pandas 2.2.3
pillow 10.4.0
pip 24.3.1
pipdeptree 2.24.0
psutil 5.9.8
pycparser 2.22
pydantic 2.10.3
pydantic_core 2.27.1
pydub 0.25.1
Pygments 2.18.0
PyMuPDF 1.25.0
pyparsing 3.2.0
PySocks 1.7.1
python-dateutil 2.9.0.post0
python-docx 1.1.2
python-multipart 0.0.19
python-pptx 1.0.2
pytz 2024.2
PyYAML 6.0.2
referencing 0.35.1
regex 2024.11.6
requests 2.32.3
rich 13.9.4
rpds-py 0.22.3
ruff 0.8.2
safetensors 0.4.5
semantic-version 2.10.0
setuptools 75.6.0
shellingham 1.5.4
six 1.17.0
sniffio 1.3.1
spaces 0.28.3
starlette 0.38.6
sympy 1.13.1
tiktoken 0.8.0
tokenizers 0.19.1
tomlkit 0.12.0
torch 2.5.1
torchaudio 2.5.1
torchvision 0.20.1
tqdm 4.67.1
transformers 4.40.0
triton 3.1.0
typer 0.15.1
typing_extensions 4.12.2
tzdata 2024.2
urllib3 2.2.3
uvicorn 0.32.1
websockets 11.0.3
wheel 0.45.1
XlsxWriter 3.2.0
zstandard 0.23.0
2
then using this run.py(modified from jupyter, using local model)
import torch
from PIL import Image
import gradio as gr
import spaces
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
import os
from threading import Thread
import pymupdf
import docx
from pptx import Presentation
print(f"torch version {torch.__version__} cuda version {torch.version.cuda}")
MODEL_LIST = ["nikravan/glm-4vq"]
HF_TOKEN = os.environ.get("HF_TOKEN", None)
MODEL_ID = MODEL_LIST[0]
MODEL_NAME = "GLM-4vq"
TITLE = "<h1>3ML-bot</h1>"
DESCRIPTION = f"""
<center>
<p>😊 A MultiModal MultiLingual(MMML) Chat.
<br>
🚀 MODEL NOW: <a href="https://hf.co/{MODEL_ID}">{MODEL_NAME}</a>
</center>"""
CSS = """
h1 {
text-align: center;
display: block;
}
"""
model = AutoModelForCausalLM.from_pretrained(
"/home/ubuntu/glm-4vq",
torch_dtype=torch.bfloat16,
low_cpu_mem_usage=True,
trust_remote_code=True
)
tokenizer = AutoTokenizer.from_pretrained("/home/ubuntu/glm-4vq", trust_remote_code=True)
model.eval()
def extract_text(path):
return open(path, 'r').read()
def extract_pdf(path):
doc = pymupdf.open(path)
text = ""
for page in doc:
text += page.get_text()
print(f"PDF文字解析完成",text)
return text
def extract_docx(path):
doc = docx.Document(path)
data = []
for paragraph in doc.paragraphs:
data.append(paragraph.text)
content = '\n\n'.join(data)
return content
def extract_pptx(path):
prs = Presentation(path)
text = ""
for slide in prs.slides:
for shape in slide.shapes:
if hasattr(shape, "text"):
text += shape.text + "\n"
return text
def mode_load(path):
choice = ""
file_type = path.split(".")[-1]
print(file_type)
if file_type in ["pdf", "txt", "py", "docx", "pptx", "json", "cpp", "md"]:
if file_type.endswith("pdf"):
content = extract_pdf(path)
elif file_type.endswith("docx"):
content = extract_docx(path)
elif file_type.endswith("pptx"):
content = extract_pptx(path)
else:
content = extract_text(path)
choice = "doc"
print(content[:100])
return choice, content[:5000]
elif file_type in ["png", "jpg", "jpeg", "bmp", "tiff", "webp"]:
content = Image.open(path).convert('RGB')
choice = "image"
return choice, content
else:
raise gr.Error("Oops, unsupported files.")
@spaces.GPU()
def stream_chat(message, history: list, temperature: float, max_length: int, top_p: float, top_k: int, penalty: float):
print(f'message is - {message}')
print(f'history is - {history}')
conversation = []
prompt_files = []
if message["files"]:
choice, contents = mode_load(message["files"][-1])
if choice == "image":
conversation.append({"role": "user", "image": contents, "content": message['text']})
elif choice == "doc":
format_msg = contents + "\n\n\n" + "{} files uploaded.\n" + message['text']
conversation.append({"role": "user", "content": format_msg})
else:
if len(history) == 0:
contents = None
conversation.append({"role": "user", "content": message['text']})
else:
for prompt, answer in history:
if answer is None:
prompt_files.append(prompt[0])
conversation.extend([{"role": "user", "content": ""}, {"role": "assistant", "content": ""}])
else:
conversation.extend([{"role": "user", "content": prompt}, {"role": "assistant", "content": answer}])
if len(prompt_files) > 0:
choice, contents = mode_load(prompt_files[-1])
else:
choice = ""
conversation.append({"role": "user", "image": "", "content": message['text']})
if choice == "image":
conversation.append({"role": "user", "image": contents, "content": message['text']})
elif choice == "doc":
format_msg = contents + "\n\n\n" + "{} files uploaded.\n" + message['text']
conversation.append({"role": "user", "content": format_msg})
print(f"Conversation is -\n{conversation}")
input_ids = tokenizer.apply_chat_template(
conversation,
tokenize=True,
add_generation_prompt=True,
return_tensors="pt",
return_dict=True
) # .to(model.device)
streamer = TextIteratorStreamer(tokenizer, timeout=60.0, skip_prompt=True, skip_special_tokens=True)
generate_kwargs = dict(
max_length=max_length,
streamer=streamer,
do_sample=True,
top_p=top_p,
top_k=top_k,
temperature=temperature,
repetition_penalty=penalty,
eos_token_id=[151329, 151336, 151338],
)
gen_kwargs = {**input_ids, **generate_kwargs}
with torch.no_grad():
thread = Thread(target=model.generate, kwargs=gen_kwargs)
thread.start()
buffer = ""
for new_text in streamer:
buffer += new_text
yield buffer
chatbot = gr.Chatbot()
chat_input = gr.MultimodalTextbox(
interactive=True,
placeholder="Enter message or upload a file ...",
show_label=False,
)
EXAMPLES = [
[{"text": "Write a poem about spring season in French Language", }],
[{"text": "what does this chart mean?", "files": ["sales.png"]}],
[{"text": "¿Qué está escrito a mano en esta foto?", "files": ["receipt1.png"]}],
[{"text": "در مورد این عکس توضیح بده و بگو این چه فصلی می تواند باشد", "files": ["nature.jpg"]}]
]
with gr.Blocks(css=CSS, theme="soft", fill_height=True) as demo:
gr.HTML(TITLE)
gr.HTML(DESCRIPTION)
gr.ChatInterface(
fn=stream_chat,
multimodal=True,
textbox=chat_input,
chatbot=chatbot,
fill_height=True,
additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),
additional_inputs=[
gr.Slider(
minimum=0,
maximum=1,
step=0.1,
value=0.8,
label="Temperature",
render=False,
),
gr.Slider(
minimum=1024,
maximum=8192,
step=1,
value=4096,
label="Max Length",
render=False,
),
gr.Slider(
minimum=0.0,
maximum=1.0,
step=0.1,
value=1.0,
label="top_p",
render=False,
),
gr.Slider(
minimum=1,
maximum=20,
step=1,
value=10,
label="top_k",
render=False,
),
gr.Slider(
minimum=0.0,
maximum=2.0,
step=0.1,
value=1.0,
label="Repetition penalty",
render=False,
),
],
),
gr.Examples(EXAMPLES, [chat_input])
if __name__ == "__main__":
demo.queue(api_open=False).launch(show_api=False, share=True,server_port=7860,server_name="172.31.180.211")