{"id":13429645,"url":"https://github.com/openai/CLIP","last_synced_at":"2025-03-16T03:32:02.745Z","repository":{"id":37307440,"uuid":"321960447","full_name":"openai/CLIP","owner":"openai","description":"CLIP (Contrastive Language-Image Pretraining),  Predict the most relevant text snippet given an image","archived":false,"fork":false,"pushed_at":"2024-07-23T01:30:44.000Z","size":9140,"stargazers_count":27779,"open_issues_count":241,"forks_count":3484,"subscribers_count":323,"default_branch":"main","last_synced_at":"2025-03-11T00:42:37.497Z","etag":null,"topics":["deep-learning","machine-learning"],"latest_commit_sha":null,"homepage":"","language":"Jupyter Notebook","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/openai.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-12-16T11:24:42.000Z","updated_at":"2025-03-10T23:00:48.000Z","dependencies_parsed_at":"2023-02-15T03:46:12.720Z","dependency_job_id":"baf1b88e-0e61-4f82-ab18-10b1c6fa3d56","html_url":"https://github.com/openai/CLIP","commit_stats":{"total_commits":56,"total_committers":22,"mean_commits":"2.5454545454545454","dds":0.4285714285714286,"last_synced_commit":"dcba3cb2e2827b402d2701e7e1c7d9fed8a20ef1"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openai%2FCLIP","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openai%2FCLIP/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openai%2FCLIP/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openai%2FCLIP/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/openai","download_url":"https://codeload.github.com/openai/CLIP/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243822309,"owners_count":20353496,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["deep-learning","machine-learning"],"created_at":"2024-07-31T02:00:43.109Z","updated_at":"2025-03-16T03:32:02.174Z","avatar_url":"https://github.com/openai.png","language":"Jupyter Notebook","readme":"# CLIP\n\n[[Blog]](https://openai.com/blog/clip/) [[Paper]](https://arxiv.org/abs/2103.00020) [[Model Card]](model-card.md) [[Colab]](https://colab.research.google.com/github/openai/clip/blob/master/notebooks/Interacting_with_CLIP.ipynb)\n\nCLIP (Contrastive Language-Image Pre-Training) is a neural network trained on a variety of (image, text) pairs. It can be instructed in natural language to predict the most relevant text snippet, given an image, without directly optimizing for the task, similarly to the zero-shot capabilities of GPT-2 and 3. We found CLIP matches the performance of the original ResNet50 on ImageNet “zero-shot” without using any of the original 1.28M labeled examples, overcoming several major challenges in computer vision.\n\n\n\n## Approach\n\n![CLIP](CLIP.png)\n\n\n\n## Usage\n\nFirst, [install PyTorch 1.7.1](https://pytorch.org/get-started/locally/) (or later) and torchvision, as well as small additional dependencies, and then install this repo as a Python package. On a CUDA GPU machine, the following will do the trick:\n\n```bash\n$ conda install --yes -c pytorch pytorch=1.7.1 torchvision cudatoolkit=11.0\n$ pip install ftfy regex tqdm\n$ pip install git+https://github.com/openai/CLIP.git\n```\n\nReplace `cudatoolkit=11.0` above with the appropriate CUDA version on your machine or `cpuonly` when installing on a machine without a GPU.\n\n```python\nimport torch\nimport clip\nfrom PIL import Image\n\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nmodel, preprocess = clip.load(\"ViT-B/32\", device=device)\n\nimage = preprocess(Image.open(\"CLIP.png\")).unsqueeze(0).to(device)\ntext = clip.tokenize([\"a diagram\", \"a dog\", \"a cat\"]).to(device)\n\nwith torch.no_grad():\n    image_features = model.encode_image(image)\n    text_features = model.encode_text(text)\n    \n    logits_per_image, logits_per_text = model(image, text)\n    probs = logits_per_image.softmax(dim=-1).cpu().numpy()\n\nprint(\"Label probs:\", probs)  # prints: [[0.9927937  0.00421068 0.00299572]]\n```\n\n\n## API\n\nThe CLIP module `clip` provides the following methods:\n\n#### `clip.available_models()`\n\nReturns the names of the available CLIP models.\n\n#### `clip.load(name, device=..., jit=False)`\n\nReturns the model and the TorchVision transform needed by the model, specified by the model name returned by `clip.available_models()`. It will download the model as necessary. The `name` argument can also be a path to a local checkpoint.\n\nThe device to run the model can be optionally specified, and the default is to use the first CUDA device if there is any, otherwise the CPU. When `jit` is `False`, a non-JIT version of the model will be loaded.\n\n#### `clip.tokenize(text: Union[str, List[str]], context_length=77)`\n\nReturns a LongTensor containing tokenized sequences of given text input(s). This can be used as the input to the model\n\n---\n\nThe model returned by `clip.load()` supports the following methods:\n\n#### `model.encode_image(image: Tensor)`\n\nGiven a batch of images, returns the image features encoded by the vision portion of the CLIP model.\n\n#### `model.encode_text(text: Tensor)`\n\nGiven a batch of text tokens, returns the text features encoded by the language portion of the CLIP model.\n\n#### `model(image: Tensor, text: Tensor)`\n\nGiven a batch of images and a batch of text tokens, returns two Tensors, containing the logit scores corresponding to each image and text input. The values are cosine similarities between the corresponding image and text features, times 100.\n\n\n\n## More Examples\n\n### Zero-Shot Prediction\n\nThe code below performs zero-shot prediction using CLIP, as shown in Appendix B in the paper. This example takes an image from the [CIFAR-100 dataset](https://www.cs.toronto.edu/~kriz/cifar.html), and predicts the most likely labels among the 100 textual labels from the dataset.\n\n```python\nimport os\nimport clip\nimport torch\nfrom torchvision.datasets import CIFAR100\n\n# Load the model\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nmodel, preprocess = clip.load('ViT-B/32', device)\n\n# Download the dataset\ncifar100 = CIFAR100(root=os.path.expanduser(\"~/.cache\"), download=True, train=False)\n\n# Prepare the inputs\nimage, class_id = cifar100[3637]\nimage_input = preprocess(image).unsqueeze(0).to(device)\ntext_inputs = torch.cat([clip.tokenize(f\"a photo of a {c}\") for c in cifar100.classes]).to(device)\n\n# Calculate features\nwith torch.no_grad():\n    image_features = model.encode_image(image_input)\n    text_features = model.encode_text(text_inputs)\n\n# Pick the top 5 most similar labels for the image\nimage_features /= image_features.norm(dim=-1, keepdim=True)\ntext_features /= text_features.norm(dim=-1, keepdim=True)\nsimilarity = (100.0 * image_features @ text_features.T).softmax(dim=-1)\nvalues, indices = similarity[0].topk(5)\n\n# Print the result\nprint(\"\\nTop predictions:\\n\")\nfor value, index in zip(values, indices):\n    print(f\"{cifar100.classes[index]:\u003e16s}: {100 * value.item():.2f}%\")\n```\n\nThe output will look like the following (the exact numbers may be slightly different depending on the compute device):\n\n```\nTop predictions:\n\n           snake: 65.31%\n          turtle: 12.29%\n    sweet_pepper: 3.83%\n          lizard: 1.88%\n       crocodile: 1.75%\n```\n\nNote that this example uses the `encode_image()` and `encode_text()` methods that return the encoded features of given inputs.\n\n\n### Linear-probe evaluation\n\nThe example below uses [scikit-learn](https://scikit-learn.org/) to perform logistic regression on image features.\n\n```python\nimport os\nimport clip\nimport torch\n\nimport numpy as np\nfrom sklearn.linear_model import LogisticRegression\nfrom torch.utils.data import DataLoader\nfrom torchvision.datasets import CIFAR100\nfrom tqdm import tqdm\n\n# Load the model\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nmodel, preprocess = clip.load('ViT-B/32', device)\n\n# Load the dataset\nroot = os.path.expanduser(\"~/.cache\")\ntrain = CIFAR100(root, download=True, train=True, transform=preprocess)\ntest = CIFAR100(root, download=True, train=False, transform=preprocess)\n\n\ndef get_features(dataset):\n    all_features = []\n    all_labels = []\n    \n    with torch.no_grad():\n        for images, labels in tqdm(DataLoader(dataset, batch_size=100)):\n            features = model.encode_image(images.to(device))\n\n            all_features.append(features)\n            all_labels.append(labels)\n\n    return torch.cat(all_features).cpu().numpy(), torch.cat(all_labels).cpu().numpy()\n\n# Calculate the image features\ntrain_features, train_labels = get_features(train)\ntest_features, test_labels = get_features(test)\n\n# Perform logistic regression\nclassifier = LogisticRegression(random_state=0, C=0.316, max_iter=1000, verbose=1)\nclassifier.fit(train_features, train_labels)\n\n# Evaluate using the logistic regression classifier\npredictions = classifier.predict(test_features)\naccuracy = np.mean((test_labels == predictions).astype(float)) * 100.\nprint(f\"Accuracy = {accuracy:.3f}\")\n```\n\nNote that the `C` value should be determined via a hyperparameter sweep using a validation split.\n\n\n## See Also\n\n* [OpenCLIP](https://github.com/mlfoundations/open_clip): includes larger and independently trained CLIP models up to ViT-G/14\n* [Hugging Face implementation of CLIP](https://huggingface.co/docs/transformers/model_doc/clip): for easier integration with the HF ecosystem\n","funding_links":[],"categories":["Machine Learning Models","4 Reasoning Techniques","Jupyter Notebook","HarmonyOS","👋 Hello","2 Foundation Models","Summary","Models","Resources","Papers","Repos","Projects","PyTorch Models","largemodel","machine-learning","Image Processing","Data Analysis","🎨 Multimodal \u0026 Specialized Models","Voice \u0026 Multimodal (local) (16)","多模态嵌入 (Multimodal Embeddings)"],"sub_categories":["4.1 Pre-Training","Windows Manager","2.3 Multimodal Foundation Models","[TVCG24] NIS-SLAM: Neural Implicit Semantic RGB-D SLAM for 3D Consistent Scene Understanding","2022","Global AI Projects","Computer Vision","Vector Store Tutorials","Foundational Vision Models","视频 (Video)"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fopenai%2FCLIP","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fopenai%2FCLIP","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fopenai%2FCLIP/lists"}