Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reuse Ollama cached image when available #782

Merged
merged 5 commits into from
Feb 11, 2025
Merged

Conversation

kush-gupt
Copy link
Contributor

@kush-gupt kush-gupt commented Feb 10, 2025

Created a new function called in_existing_cache to take in a model name and tag, search a default Ollama cache and see if there's a matching model layer to symlink in the ramalama store.

Allows the process of someone running ollama to use ramalama with no model pulls!

$ ollama ls
NAME                                   ID              SIZE      MODIFIED      
starcoder2:3b                          9f4ae0aff61e    1.7 GB    9 minutes ago    
sroecker/nuextract-tiny-v1.5:latest    be09317bfbbb    994 MB    7 hours ago      
deepseek-r1:32b                        38056bbcbb2d    19 GB     3 weeks ago      
qwen2.5-coder:32b                      4bd6cbf2d094    19 GB     2 months ago     
nomic-embed-text:latest                0a109f422b47    274 MB    8 months ago     

$ ramalama ls
NAME MODIFIED SIZE

$ ramalama run starcoder2:3b 
> We have a cache and didn't have to pull the model down
...

$ ramalama ls
NAME                   MODIFIED       SIZE   
ollama://starcoder2:3b 15 seconds ago 1.59 GB

Directory structure would look like:

$ ls -l $HOME/.local/share/ramalama/models/ollama                                                       
total 0
lrwxr-xr-x@ 1 kugupta  staff  96 Feb 10 16:57 starcoder2:3b -> ../../repos/ollama/blobs/sha256:28bfdfaeba9f51611c00ed322ba684ce6db076756dbc46643f98a8a748c5199e

$ ls -l $HOME/.local/share/ramalama/repos/ollama/blobs 
total 16
lrwxr-xr-x@ 1 kugupta  staff  107 Feb 10 16:57 sha256:28bfdfaeba9f51611c00ed322ba684ce6db076756dbc46643f98a8a748c5199e -> /Users/kugupta/.ollama/models/blobs/sha256-28bfdfaeba9f51611c00ed322ba684ce6db076756dbc46643f98a8a748c5199e

Summary by Sourcery

New Features:

  • Ramalama can now use models from the local Ollama cache without pulling them.

Copy link
Contributor

sourcery-ai bot commented Feb 10, 2025

Reviewer's Guide by Sourcery

This pull request implements a caching mechanism that reuses a locally cached Ollama model layer instead of re-downloading it. The changes include the addition of a function to check for an existing cache and modifications in the pull process to leverage the cache by symlinking the local layer, with retry logic on checksum mismatches if necessary.

Sequence diagram for reusing cached Ollama model layer

sequenceDiagram
    participant PB as pull_blob
    participant IEC as in_existing_cache
    participant DF as download_file
    participant VC as verify_checksum
    participant RC as run_cmd

    PB->>IEC: Call in_existing_cache(model_name, model_tag)
    alt Cache Found
      IEC-->>PB: local_blob
      PB->>RC: run_cmd(ln -sf local_blob, layer_blob_path)
    else No Cache Found
      IEC-->>PB: None
      PB->>DF: download_file(url, layer_blob_path)
      PB->>VC: verify_checksum(layer_blob_path)
      alt Checksum passes
         note right of VC: Proceed with downloaded blob
      else Checksum mismatch
         PB->>PB: Print error and remove layer_blob_path
         PB->>DF: download_file(url, layer_blob_path) again
         PB->>VC: verify_checksum(layer_blob_path) again
         alt Second Checksum passes
            note right of VC: Proceed after re-download
         else Second Checksum fails
            PB->>PB: Raise ValueError
         end
      end
    end
Loading

File-Level Changes

Change Details Files
Introduce cache lookup and symlink logic for model layers.
  • Added a new function 'in_existing_cache' that takes the model name and tag, searches predefined Ollama cache directories, and retrieves the local model layer if available.
  • Modified the pull_blob function to first attempt to use the cached layer by creating a symbolic link instead of downloading the blob.
  • Maintained fallback to downloading and checksum verification if no cached blob is found.
  • Included retry logic that re-downloads the blob if the first download fails the checksum verification.
ramalama/ollama.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @kush-gupt - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider adding a check to ensure the layer_blob_path exists after the symlink operation in pull_blob.
  • The in_existing_cache function could be improved by using os.path.expanduser to handle the home directory path.
Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

ramalama/ollama.py Outdated Show resolved Hide resolved
@rhatdan
Copy link
Member

rhatdan commented Feb 11, 2025

@kush-gupt Thanks great work.

Could you verify what happens if Ramalama or Ollama removes the model.

ramalama pull starcoder2:3b 
ramalama ls
ramalama rm starcoder2:3b
ramalama ls
ollama ls
ramalama pull starcoder2:3b 
ramalama ls
ollama rm starcoder2:3b
ramalama ls
ollama ls

Want to make sure if ollama removes the model, then ramalama no longer has it?
Similarly if ramalama removes the model, then ollama still has it.

It might make more sense to have hard links then softlinks. Then ollama removing it would not effect ramalama or vice versa. Of course do hard links and soft links work well on Mac andWindows?

@ericcurtin
Copy link
Collaborator

ericcurtin commented Feb 11, 2025

The code looks good and the core "ramalama run/ramalama serve" would work, I guess we are probably capable of corrupting Ollama model store via RamaLama with "ramalama rm" etc. ?

@ericcurtin
Copy link
Collaborator

@rhatdan had a similar thought at the same time... 😄

@ericcurtin
Copy link
Collaborator

ericcurtin commented Feb 11, 2025

@kush-gupt Thanks great work.

Could you verify what happens if Ramalama or Ollama removes the model.

ramalama pull starcoder2:3b 
ramalama ls
ramalama rm starcoder2:3b
ramalama ls
ollama ls
ramalama pull starcoder2:3b 
ramalama ls
ollama rm starcoder2:3b
ramalama ls
ollama ls

Want to make sure if ollama removes the model, then ramalama no longer has it? Similarly if ramalama removes the model, then ollama still has it.

It might make more sense to have hard links then softlinks. Then ollama removing it would not effect ramalama or vice versa. Of course do hard links and soft links work well on Mac andWindows?

RamaLama does not currently have the ability to fully remove an Ollama model from a Ollama model store, since we only look at the .gguf part, I think with the current code, we could only partially remove an Ollama model from it's store. Writing/removing things in the Ollama store in general seems messy, it's not on our turf.

My initial thoughs would be, we just remove our link to the Ollama registry (maybe print a message that we won't manipulate the Ollama model store). Links to the Ollama model store, seem safe...

print(f"Checksum mismatch for blob {layer_blob_path}, retrying download...")
os.remove(layer_blob_path)
local_blob = in_existing_cache(model_name, model_tag)
if local_blob is not None:
Copy link
Collaborator

@ericcurtin ericcurtin Feb 11, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the:

if local_blob is not None:

case, we seem to call ln -sf twice, should we call it once?

In the rm case in an Ollama-stored object, I propose we just remove the symlink part:

local_blob

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree, I think we should only remove the ramalama content on ramalama rm. But on ollama rm ramalama can end up in a bad state as well, which I think we should take care of also. ramalama ls should either ignore hanging symlinks or remove them.

BTW I have seen the database get futz up by breaking removing of images, and we don't handle it cracefully. I had to find the symlink and rm -f it .

Copy link
Collaborator

@ericcurtin ericcurtin Feb 11, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After thinking through this, I understand the double symlink now, once for the sha256 and a second time for the named version, I think the rm should handle this without touching the Ollama store, but we should test to be sure.

@rhatdan
Copy link
Member

rhatdan commented Feb 11, 2025

Once this gets in, we should do the same for Huggingface database.

I think this is partially what @benoitf wants.

@ericcurtin ericcurtin merged commit 6f0783c into containers:main Feb 11, 2025
16 checks passed
if layer["mediaType"] == "application/vnd.ollama.image.model":
layer_digest = layer["digest"]
ollama_digest_path = os.path.join(cache_dir, 'blobs', layer_digest)
if os.path.exists(str(ollama_digest_path).replace(':','-')):
Copy link
Collaborator

@ericcurtin ericcurtin Feb 11, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we ever make breaking changes to the model store which I suspect we will, we should change ':' to '-'on disk. ':' doesn't work on Windows filesystems for one. But that's should be a hidden detail to the user, they should use ':'

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lets make the change now, when we have not released 1.0, For now we can handle both : and -.

@kush-gupt
Copy link
Contributor Author

ramalama pull starcoder2:3b 
ramalama ls
ramalama rm starcoder2:3b
ramalama ls
ollama ls
$ ollama ls
NAME                                   ID              SIZE      MODIFIED     
qwen:1.8b                              b6e8ec2e7126    1.1 GB    10 hours ago    
starcoder2:3b                          9f4ae0aff61e    1.7 GB    15 hours ago    
...

$ ramalama ls
NAME                       MODIFIED     SIZE    
ollama://qwen:1.8b         10 hours ago 1.04 GB 
ollama://deepseek-r1:32b   10 hours ago 18.49 GB
ollama://qwen2.5-coder:32b 10 hours ago 18.49 GB

$ ramalama rm starcoder2:3b
Error: removing starcoder2:3b: [Errno 2] No such file or directory: '/Users/kugupta/.local/share/ramalama/models/ollama/starcoder2:3b

$ ramalama ls
NAME                       MODIFIED     SIZE    
ollama://qwen:1.8b         10 hours ago 1.04 GB 
ollama://deepseek-r1:32b   10 hours ago 18.49 GB
ollama://qwen2.5-coder:32b 10 hours ago 18.49 GB

$ ollama ls
NAME                                   ID              SIZE      MODIFIED     
qwen:1.8b                              b6e8ec2e7126    1.1 GB    10 hours ago    
starcoder2:3b                          9f4ae0aff61e    1.7 GB    15 hours ago    
...
ramalama pull starcoder2:3b 
ramalama ls
ollama rm starcoder2:3b
ramalama ls
ollama ls
$ollama ls
NAME                                   ID              SIZE      MODIFIED      
starcoder2:3b                          9f4ae0aff61e    1.7 GB    15 hours ago    
 ...

$ ramalama pull starcoder2:3b

$ ramalama ls
NAME                       MODIFIED      SIZE    
...
ollama://starcoder2:3b     5 seconds ago 1.59 GB 
...

$ ollama rm starcoder2:3b
deleted 'starcoder2:3b'

$ ramalama ls            
Error: [Errno 2] No such file or directory: 'ollama/starcoder2:3b

$ ollama ls
NAME                                   ID              SIZE      MODIFIED     
qwen:1.8b                              b6e8ec2e7126    1.1 GB    10 hours ago    
sroecker/nuextract-tiny-v1.5:latest    be09317bfbbb    994 MB    22 hours ago    
deepseek-r1:32b                        38056bbcbb2d    19 GB     3 weeks ago     
qwen2.5-coder:32b                      4bd6cbf2d094    19 GB     2 months ago    
nomic-embed-text:latest                0a109f422b47    274 MB    8 months ago   

Want to make sure if ollama removes the model, then ramalama no longer has it? Similarly if ramalama removes the model, then ollama still has it.
This is happening currently, but I noticed there isn't a catch for a dangling link when doing ramalama ls (it only checks if it's a link, not if it exists) so I will send some error catching there.

It might make more sense to have hard links then softlinks. Then ollama removing it would not effect ramalama or vice versa. Of course do hard links and soft links work well on Mac andWindows?

It could be a hard link from the Ollama model blob to the ramalama blob store, retaining the ability for ramalama rm to work and not affect Ollama but adding the ability for ramalama to keep the model storage after a ollama rm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants