Skip to content

RuntimeError: Cannot call numpy() on Tensor that requires grad  #16

@woctezuma

Description

@woctezuma

When running the first usage example on a machine without GPU (on Heroku), I have encountered an error message.

This is the usage example:

import torch
import clip
from PIL import Image

device = "cuda" if torch.cuda.is_available() else "cpu"
model, preprocess = clip.load("ViT-B/32", device=device)

image = preprocess(Image.open("CLIP.png")).unsqueeze(0).to(device)
text = clip.tokenize(["a diagram", "a dog", "a cat"]).to(device)

with torch.no_grad():
    image_features = model.encode_image(image)
    text_features = model.encode_text(text)
    
    logits_per_image, logits_per_text = model(image, text)
    probs = logits_per_image.softmax(dim=-1).cpu().numpy()

print("Label probs:", probs)  # prints: [[0.9927937  0.00421068 0.00299572]]

This is the error message:

RuntimeError: Cannot call numpy() on Tensor that requires grad 

I have followed the recommendation displayed along the error message, and changed this line from:

    probs = logits_per_image.softmax(dim=-1).cpu().numpy()

to:

    probs = logits_per_image.softmax(dim=-1).cpu().detach().numpy()

I have no idea whether the issue is specific to my machine, but I might as well mention it here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions