René's URL Explorer Experiment


Title: Slow when logits_all=True, inconsistent logprobs and solutions · Issue #1983 · abetlen/llama-cpp-python · GitHub

Open Graph Title: Slow when logits_all=True, inconsistent logprobs and solutions · Issue #1983 · abetlen/llama-cpp-python

X Title: Slow when logits_all=True, inconsistent logprobs and solutions · Issue #1983 · abetlen/llama-cpp-python

Description: Environment Lastest version by 2025.03.26 Issue I tried to use this library to record logits of my gguf model. But it seemed to be some errors on the return value of Llama.__call__(). And the process of recording logits is too slow. Then...

Open Graph Description: Environment Lastest version by 2025.03.26 Issue I tried to use this library to record logits of my gguf model. But it seemed to be some errors on the return value of Llama.__call__(). And the proce...

X Description: Environment Lastest version by 2025.03.26 Issue I tried to use this library to record logits of my gguf model. But it seemed to be some errors on the return value of Llama.__call__(). And the proce...

Opengraph URL: https://github.com/abetlen/llama-cpp-python/issues/1983

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Slow when logits_all=True, inconsistent logprobs and solutions","articleBody":"# Environment\nLastest version by 2025.03.26\n# Issue\nI tried to use this library to record logits of my gguf model. But it seemed to be some errors on the return value of Llama.\\_\\_call\\_\\_(). And the process of recording logits is too slow.\n\nThen I dived into this problem. I found that the \"token_logprobs\" in the return value of Llama.\\_\\_call\\_\\_() are not the log probabilities of the current token generated on the current position. The returned \"token_logprobs\" are actually the log probabilities of the current token generated by the model after receiving the current token.\n\nI wrote two python program to verify it.\n``` python\nfrom llama_cpp import Llama\n\nmodel_path = \"\" #gguf models\n\nprompt = \"Once upon a time,\"\n\nmodel = Llama(\n    model_path= model_path,\n    n_gpu_layers=-1, \n    n_ctx=2048,\n    logits_all=True,\n    main_gpu=0,\n    verbose=False\n)\n\nresponse = model(\n    prompt= prompt, \n    max_tokens = 1, \n    echo=True,\n    logprobs = 1,\n    temperature = 0,\n)\n\nlogprobs = response['choices'][0]['logprobs']\ntokens = logprobs['tokens']\ntoken_logprobs = logprobs['token_logprobs']\ntop_logprobs = logprobs['top_logprobs']\n\nprint(response)\nfor i in range(len(tokens)):\n    print(\"prob_ln = \", token_logprobs[i], \"Token = \", tokens[i])\n\n\nprint(len(response['choices'][0]['logprobs']['top_logprobs']))\n```\n``` python\nimport torch\nimport torch.nn.functional as F\nimport transformers\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\nmodel_path = \"\" # hf models.\nprompt = \"Once upon a time,\"\nmodel = AutoModelForCausalLM.from_pretrained(model_path, torch_dtype='auto', revision=\"main\")\ntokenizer = AutoTokenizer.from_pretrained(model_path, torch_dtype='auto')\n\ninputs = tokenizer(prompt, return_tensors=\"pt\")\ninput_ids = inputs[\"input_ids\"]\n\nprint(input_ids)\nwith torch.no_grad():\n    outputs = model(input_ids=input_ids)\n\nlogits = F.log_softmax(outputs.logits, dim=-1)\nprint(logits)\nlogits = torch.squeeze(logits)\n\nfor i in range(logits.shape[0]): \n    prob_ln = logits[i-1, input_ids[0, i]].item() #replace \"i-1\" with \"i\", you will get results same as the Llama version\n    token = tokenizer.decode(input_ids[0, i]) \n    print(f\"Position {i}: prob_ln = {prob_ln}, Token = '{token}', TokenID = {input_ids[0, i]}\")\n```\nIf you use the two models only different on format, you will found totaly different outputs.  And you can modify the code based on my comments to verify my conclusion.\n# Solutions\nI got a rough solution for my need. But I am busy recently, unable to write thorough codes. Hope you guys can complement it to the project.\nFor the efficiency, I found a sort for a vocab size tensor in Llama.\\_create_completion( See the picture below ). But for my need, I only need one top_token_logprobs. This sort costs most time in my program. I use torch.max to fix it. For thorough need, you may add some specific optimization when the parameter \"logprobs\" is small.\nFor the inconsistent logprobs, you just need to change \"int(token)\"( See the picture below ) to the \"pre_token\".\n![Image](https://github.com/user-attachments/assets/e3a28710-398f-4173-a654-3a970934a2f5)\nAnd here is my solution. But it only works for recording one top_tokens. You can replace them to the correspond space in llama.py if you have the same need.\n``` python\n    logprobs_or_none: Optional[CompletionLogprobs] = None\n        if logprobs is not None:\n            text_offset = 0 if echo else len(prompt)\n            token_offset = 0 if echo else len(prompt_tokens[1:])\n            text_offsets: List[int] = []\n            token_logprobs: List[Optional[float]] = []\n            tokens: List[str] = []\n            top_logprobs: List[Optional[Dict[str, float]]] = []\n\n            if echo:\n                # Remove leading BOS token if exists\n                all_tokens = (\n                    prompt_tokens[1 if prompt_tokens[0] == self.token_bos() else 0 :]\n                    + completion_tokens\n                )\n            else:\n                all_tokens = completion_tokens\n\n            all_token_strs = [\n                self.detokenize([token], prev_tokens=all_tokens[:i]).decode(\n                    \"utf-8\", errors=\"ignore\"\n                )\n                for i, token in enumerate(all_tokens)\n            ]\n            all_logprobs = Llama.logits_to_logprobs(self._scores)[token_offset:]\n            # TODO: may be able to change this loop to use np.take_along_dim\n            token_logprobs = [0.0]\n            top_logprobs = [{}]\n            for idx, (token, token_str, logprobs_token) in enumerate(\n                zip(all_tokens, all_token_strs, all_logprobs)\n            ):\n                if token == bos_token_id:\n                    continue\n                text_offsets.append(\n                    text_offset\n                    + len(\n                        self.detokenize(all_tokens[:idx]).decode(\n                            \"utf-8\", errors=\"ignore\"\n                        )\n                    )\n                )\n                tokens.append(token_str)\n                # sorted_logprobs = list(\n                #     sorted(\n                #         zip(logprobs_token, range(len(logprobs_token))), reverse=True\n                #     )\n                # )\n                logprobs_token_tmp = torch.tensor(logprobs_token)\n                max_logprob, max_indix = torch.max(logprobs_token_tmp, dim=0)\n                if(idx+1 != len(all_tokens)):\n                    token_logprobs.append(logprobs_token[int(all_tokens[idx+1])])\n                # print(token, logprobs_token[int(token)])\n                top_logprob: Optional[Dict[str, float]] = {\n                    # self.detokenize([i], prev_tokens=all_tokens[:idx]).decode(\n                        # \"utf-8\", errors=\"ignore\"\n                    # ): logprob\n                    self.detokenize([max_indix], prev_tokens=all_tokens[:idx]).decode(\n                        \"utf-8\", errors=\"ignore\"\n                    ): max_logprob\n                }\n                # top_logprob.update({token_str: logprobs_token[int(token)]})\n                top_logprobs.append(top_logprob)\n            # Weird idosincracy of the OpenAI API where\n            # token_logprobs and top_logprobs are null for\n            # the first token.\n            # if echo and len(all_tokens) > 0:\n            #     token_logprobs[0] = None\n            #     top_logprobs[0] = None\n            logprobs_or_none = {\n                \"tokens\": tokens,\n                \"text_offset\": text_offsets,\n                \"token_logprobs\": token_logprobs,\n                \"top_logprobs\": top_logprobs,\n            }\n```\n","author":{"url":"https://github.com/For-rest2005","@type":"Person","name":"For-rest2005"},"datePublished":"2025-03-26T04:58:06Z","url":"https://github.com/abetlen/llama-cpp-python/issues/1983"}

react-profiling0
react-import-mapreact,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322
route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:e5451ce7-c4f3-5c29-19d0-53a3e58de9a8
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idC254:37308E:12E409E:1803FE7:6AFF98A4
html-safe-nonce090e0073ea5cebec57da4206816dfa5b3bfdeba8911d1d67ea54970169c5aa42
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJDMjU0OjM3MzA4RToxMkU0MDlFOjE4MDNGRTc6NkFGRjk4QTQiLCJ2aXNpdG9yX2lkIjoiMzk0NjU0MDU4ODQ2MzAwMzgxMiIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmacb63d497aef4ca52f7dcf01a0744a07254fc2a3b07eaa286419f206455b21d48c
hovercard-subject-tagissue:2948401219
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/abetlen/llama-cpp-python/1983/issue_layout
twitter:imagehttps://opengraph.githubassets.com/f2b64e0620ff023e62e947807ddd393012c6f19cd932262220cd155b3f5f7a72/abetlen/llama-cpp-python/issues/1983
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/f2b64e0620ff023e62e947807ddd393012c6f19cd932262220cd155b3f5f7a72/abetlen/llama-cpp-python/issues/1983
og:image:altEnvironment Lastest version by 2025.03.26 Issue I tried to use this library to record logits of my gguf model. But it seemed to be some errors on the return value of Llama.__call__(). And the proce...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernameFor-rest2005
hostnamegithub.com
expected-hostnamegithub.com
None2c75d045e8c84b51e2ac680086a6dd1eeaf2bc15b82137d22ee5106835d6256c
turbo-cache-controlno-preview
go-importgithub.com/abetlen/llama-cpp-python git https://github.com/abetlen/llama-cpp-python.git
octolytics-dimension-user_id6826477
octolytics-dimension-user_loginabetlen
octolytics-dimension-repository_id617868717
octolytics-dimension-repository_nwoabetlen/llama-cpp-python
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id617868717
octolytics-dimension-repository_network_root_nwoabetlen/llama-cpp-python
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
release525b66d22c4f7e6bb8b62934bec198964f7e8b93
ui-targetfull
theme-color#1e2327
color-schemelight dark
react-app-nameissues

Links:

Skip to contenthttps://github.com/abetlen/llama-cpp-python/issues/1983#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fabetlen%2Fllama-cpp-python%2Fissues%2F1983
GitHubRepository hosting, code review, and collaborationhttps://github.com/platform
CopilotAI coding agent for tasks, projects, and automated workhttps://github.com/features/copilot
ActionsCI/CD and automationhttps://github.com/features/actions
Code QualityQuality analysis, fixes, and enforcementhttps://github.com/features/code-quality
CodespacesCloud development environmentshttps://github.com/features/codespaces
Code SecurityVulnerability detection and remediationhttps://github.com/security/advanced-security/code-security
Secret ProtectionSecret scanning and leak preventionhttps://github.com/security/advanced-security/secret-protection
All Featureshttps://github.com/features
Documentationhttps://docs.github.com/en
Traininghttps://learn.github.com/skills
Certificationshttps://learn.github.com/credentials
Build with Copilothttps://github.com/features/ai
Customize Copilothttps://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/customize-copilot-overview
Integrationshttps://github.com/marketplace
Trending reposhttps://github.com/trending
GitHub Sponsorshttps://github.com/open-source/sponsors
Developer articleshttps://github.com/resources/articles
ChangelogYour source for the latest features, improvements, and fixes across GitHub products, all in one place.https://github.blog/changelog/
Enterpriseshttps://github.com/enterprise
Teamhttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
See all industrieshttps://github.com/solutions/industry
Why GitHubhttps://github.com/why-github
Customer Storieshttps://github.com/customer-stories
Business insightshttps://github.com/solutions/executive-insights
Trust Centerhttps://github.com/trust-center
GitHub Advanced SecurityEnterprise-grade code securityhttps://github.com/security/advanced-security
Copilot for businessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Documentationhttps://docs.github.com/en
Resource centerhttps://github.com/resources
Bloghttps://github.blog/
Events & webinarshttps://github.com/resources/events
Community Forumhttps://github.com/orgs/community/discussions
Customer Storieshttps://github.com/customer-stories
Integrationshttps://github.com/marketplace
Customer supporthttps://help.github.com/
Traininghttps://learn.github.com/skills
GitHub Statushttps://www.githubstatus.com/
Abouthttps://github.com/about
Partnershttps://github.com/partners
Changeloghttps://github.blog/changelog/
GitHub UniverseThe event for developers, by developers — talks, workshops, and what’s next for GitHub.https://githubuniverse.com/
Pricinghttps://github.com/pricing
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fabetlen%2Fllama-cpp-python%2Fissues%2F1983
Sign uphttps://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=abetlen%2Fllama-cpp-python
Reloadhttps://github.com/abetlen/llama-cpp-python/issues/1983
Reloadhttps://github.com/abetlen/llama-cpp-python/issues/1983
Reloadhttps://github.com/abetlen/llama-cpp-python/issues/1983
abetlenhttps://github.com/abetlen
llama-cpp-pythonhttps://github.com/abetlen/llama-cpp-python
Codehttps://github.com/abetlen/llama-cpp-python
Issues600 (600)https://github.com/abetlen/llama-cpp-python/issues
Pull requests122 (122)https://github.com/abetlen/llama-cpp-python/pulls
Discussionshttps://github.com/abetlen/llama-cpp-python/discussions
Actionshttps://github.com/abetlen/llama-cpp-python/actions
Projectshttps://github.com/abetlen/llama-cpp-python/projects
Security and quality1 (1)https://github.com/abetlen/llama-cpp-python/security
Insightshttps://github.com/abetlen/llama-cpp-python/pulse
https://github.com/abetlen/llama-cpp-python
New issuehttps://github.com/login?return_to=https://github.com/abetlen/llama-cpp-python/issues/1983
New issuehttps://github.com/login?return_to=https://github.com/abetlen/llama-cpp-python/issues/1983
Slow when logits_all=True, inconsistent logprobs and solutionshttps://github.com/abetlen/llama-cpp-python/issues/1983#top
https://github.com/For-rest2005
For-rest2005https://github.com/For-rest2005
on Mar 26, 2025https://github.com/abetlen/llama-cpp-python/issues/1983#issue-2948401219
https://private-user-images.githubusercontent.com/137715572/426849405-e3a28710-398f-4173-a654-3a970934a2f5.png?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3OTUxMzU5NTIsIm5iZiI6MTc5NTEzNTY1MiwicGF0aCI6Ii8xMzc3MTU1NzIvNDI2ODQ5NDA1LWUzYTI4NzEwLTM5OGYtNDE3My1hNjU0LTNhOTcwOTM0YTJmNS5wbmc_WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTYmWC1BbXotQ3JlZGVudGlhbD1BS0lBVkNPRFlMU0E1M1BRSzRaQSUyRjIwMjYxMTIwJTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDI2MTEyMFQwMDQ3MzJaJlgtQW16LUV4cGlyZXM9MzAwJlgtQW16LVNpZ25hdHVyZT1jMzYzNjk5ZTZiMDBiNmIwMTUwZDhjYjM4N2FjYzJkMjhiMjg4ZjUzNzIzYjk2NmI3N2FhY2JlYjEyYjFhMDk2JlgtQW16LVNpZ25lZEhlYWRlcnM9aG9zdCZyZXNwb25zZS1jb250ZW50LXR5cGU9aW1hZ2UlMkZwbmcifQ.szaCIAyNNxFwDoYIexJIrrai4VMJ-c25acLPIy1Lea4
For-rest2005https://github.com/For-rest2005
on Mar 26, 2025https://github.com/abetlen/llama-cpp-python/issues/1983#event-16985917093
https://github.com/kunxiongzhu
kunxiongzhuhttps://github.com/kunxiongzhu
on Apr 6, 2025https://github.com/abetlen/llama-cpp-python/issues/1983#issuecomment-2781192277
@For-rest2005https://github.com/For-rest2005
https://github.com/For-rest2005
For-rest2005https://github.com/For-rest2005
on Apr 6, 2025https://github.com/abetlen/llama-cpp-python/issues/1983#issuecomment-2781217195
@kunxiongzhuhttps://github.com/kunxiongzhu
https://github.com/kunxiongzhu
kunxiongzhuhttps://github.com/kunxiongzhu
on Apr 7, 2025https://github.com/abetlen/llama-cpp-python/issues/1983#issuecomment-2783888173
@For-rest2005https://github.com/For-rest2005
https://github.com/For-rest2005
For-rest2005https://github.com/For-rest2005
on Apr 10, 2025https://github.com/abetlen/llama-cpp-python/issues/1983#issuecomment-2794396718
@kunxiongzhuhttps://github.com/kunxiongzhu
PRhttps://github.com/EleutherAI/lm-evaluation-harness/pull/2846
https://github.com/kunxiongzhu
kunxiongzhuhttps://github.com/kunxiongzhu
on Apr 11, 2025https://github.com/abetlen/llama-cpp-python/issues/1983#issuecomment-2795651464
@For-rest2005https://github.com/For-rest2005
https://github.com/For-rest2005
For-rest2005https://github.com/For-rest2005
on Apr 12, 2025https://github.com/abetlen/llama-cpp-python/issues/1983#issuecomment-2798842077
https://private-user-images.githubusercontent.com/137715572/433050449-efab7f9e-9d06-4501-b578-b138df94140a.png?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3OTUxMzU5NTMsIm5iZiI6MTc5NTEzNTY1MywicGF0aCI6Ii8xMzc3MTU1NzIvNDMzMDUwNDQ5LWVmYWI3ZjllLTlkMDYtNDUwMS1iNTc4LWIxMzhkZjk0MTQwYS5wbmc_WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTYmWC1BbXotQ3JlZGVudGlhbD1BS0lBVkNPRFlMU0E1M1BRSzRaQSUyRjIwMjYxMTIwJTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDI2MTEyMFQwMDQ3MzNaJlgtQW16LUV4cGlyZXM9MzAwJlgtQW16LVNpZ25hdHVyZT0yYzc1MTFjZjQ3MDVkYTRkZDI4NmNjOGMzMGQwMmI5Y2I5YWI0NzhlMDg2NTM3ODQwODcxODM0OWQ3YzA1OGJjJlgtQW16LVNpZ25lZEhlYWRlcnM9aG9zdCZyZXNwb25zZS1jb250ZW50LXR5cGU9aW1hZ2UlMkZwbmcifQ.e0Dro42OrOugWwdipAnpDujv5WuCrE9wJgsP0f9tC2I
@kunxiongzhuhttps://github.com/kunxiongzhu
Sign up for freehttps://github.com/signup?return_to=https://github.com/abetlen/llama-cpp-python/issues/1983
Sign in to commenthttps://github.com/login?return_to=https://github.com/abetlen/llama-cpp-python/issues/1983
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.