id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
142,966 | from robyn import Robyn
def index():
return "Hello World!" | null |
142,967 | from pymongo import MongoClient
from robyn import Robyn
def index():
return "Hello World!" | null |
142,968 | from pymongo import MongoClient
from robyn import Robyn
users = db.users
async def get_users():
all_users = await users.find().to_list(length=None)
return {"users": all_users} | null |
142,969 | from pymongo import MongoClient
from robyn import Robyn
users = db.users
async def add_user(request):
user_data = await request.json()
result = await users.insert_one(user_data)
return {"success": True, "inserted_id": str(result.inserted_id)} | null |
142,970 | from pymongo import MongoClient
from robyn import Robyn
users = db.users
async def get_user(request):
user_id = request.path_params["user_id"]
user = await users.find_one({"_id": user_id})
if user:
return user
else:
return {"error": "User not found"}, 404 | null |
142,972 | from robyn import Robyn
from sqlmodel import SQLModel, Session, create_engine, select
from models import Hero
def index():
return "Hello World" | null |
142,973 | from robyn import Robyn
from sqlmodel import SQLModel, Session, create_engine, select
from models import Hero
engine = create_engine("sqlite:///database.db", echo=True)
def create():
SQLModel.metadata.create_all(bind=engine)
return "created tables" | null |
142,974 | from robyn import Robyn
from sqlmodel import SQLModel, Session, create_engine, select
from models import Hero
engine = create_engine("sqlite:///database.db", echo=True)
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
secret_name: str
age: Optional[i... | null |
142,975 | from robyn import Robyn
from sqlmodel import SQLModel, Session, create_engine, select
from models import Hero
engine = create_engine("sqlite:///database.db", echo=True)
class Hero(SQLModel, table=True):
def get_data():
with Session(engine) as session:
statement = select(Hero).where(Hero.name == "Spider-Bo... | null |
142,976 | from robyn import Robyn
from prisma import Prisma
from prisma.models import User
prisma = Prisma(auto_register=True)
async def startup_handler() -> None:
await prisma.connect() | null |
142,977 | from robyn import Robyn
from prisma import Prisma
from prisma.models import User
prisma = Prisma(auto_register=True)
async def shutdown_handler() -> None:
if prisma.is_connected():
await prisma.disconnect() | null |
142,978 | from robyn import Robyn
from prisma import Prisma
from prisma.models import User
prisma = Prisma(auto_register=True)
async def h():
user = await User.prisma().create(
data={
"name": "Robert",
},
)
return user.json(indent=2) | null |
142,979 | from robyn import Robyn
import sqlite3
def index():
# your db name
conn = sqlite3.connect("example.db")
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS test")
cur.execute("CREATE TABLE test(column_1, column_2)")
res = cur.execute("SELECT name FROM sqlite_master")
th = res.fetchone()
... | null |
142,980 | import psycopg2
from robyn import Robyn
conn = psycopg2.connect(database=DB_NAME, host=DB_HOST, user=DB_USER, password=DB_PASS, port=DB_PORT)
def get_users():
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
all_users = cursor.fetchall()
return {"users": all_users} | null |
142,981 | import psycopg2
from robyn import Robyn
def index():
return "Hello World!" | null |
142,982 | from typing import Any, Dict
from robyn.robyn import Response, Headers
The provided code snippet includes necessary dependencies for implementing the `html` function. Write a Python function `def html(html: str) -> Response` to solve the following problem:
This function will help in serving a simple html string :param... | This function will help in serving a simple html string :param html str: html to serve as a response |
142,983 | from typing import Any, Dict
from robyn.robyn import Response, Headers
The provided code snippet includes necessary dependencies for implementing the `serve_html` function. Write a Python function `def serve_html(file_path: str) -> Dict[str, Any]` to solve the following problem:
This function will help in serving a si... | This function will help in serving a single html file :param file_path str: file path to serve as a response |
142,984 | from typing import Any, Dict
from robyn.robyn import Response, Headers
The provided code snippet includes necessary dependencies for implementing the `serve_file` function. Write a Python function `def serve_file(file_path: str) -> Dict[str, Any]` to solve the following problem:
This function will help in serving a fi... | This function will help in serving a file :param file_path str: file path to serve as a response |
142,985 | import os
import glob
import signal
import subprocess
import sys
import time
from typing import List
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
from robyn.logger import Colors, logger
def compile_rust_files(directory_path: str):
rust_files = glob.glob(os.path.join(di... | null |
142,986 | import os
import glob
import signal
import subprocess
import sys
import time
from typing import List
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
from robyn.logger import Colors, logger
def clean_rust_binaries(rust_binaries: List[str]):
for file in rust_binaries:
... | null |
142,987 | import sys
import nox
def tests(session):
session.run("pip", "install", "poetry==1.3.0")
session.run(
"poetry",
"export",
"--with",
"test",
"--with",
"dev",
"--without-hashes",
"--output",
"requirements.txt",
)
session.run("pip", "... | null |
142,988 | import sys
import nox
def lint(session):
session.run("pip", "install", "black", "ruff")
session.run("black", "robyn/", "integration_tests/")
session.run("ruff", "robyn/", "integration_tests/") | null |
142,989 | import argparse
import os
import random
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import wandb
import minigpt4.tasks as tasks
from minigpt4.common.config import Config
from minigpt4.common.dist_utils import get_rank, init_distributed_mode
from minigpt4.common.logger import setup_logger
from m... | null |
142,990 | import argparse
import os
import random
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import wandb
import minigpt4.tasks as tasks
from minigpt4.common.config import Config
from minigpt4.common.dist_utils import get_rank, init_distributed_mode
from minigpt4.common.logger import setup_logger
from m... | null |
142,991 | import argparse
import os
import random
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import wandb
import minigpt4.tasks as tasks
from minigpt4.common.config import Config
from minigpt4.common.dist_utils import get_rank, init_distributed_mode
from minigpt4.common.logger import setup_logger
from m... | Get runner class from config. Default to epoch-based runner. |
142,992 | import argparse
import os
import random
from collections import defaultdict
import cv2
import re
import numpy as np
from PIL import Image
import torch
import html
import gradio as gr
import torchvision.transforms as T
import torch.backends.cudnn as cudnn
from minigpt4.common.config import Config
from minigpt4.common.re... | null |
142,993 | import argparse
import os
import random
from collections import defaultdict
import cv2
import re
import numpy as np
from PIL import Image
import torch
import html
import gradio as gr
import torchvision.transforms as T
import torch.backends.cudnn as cudnn
from minigpt4.common.config import Config
from minigpt4.common.re... | null |
142,994 | import argparse
import os
import random
from collections import defaultdict
import cv2
import re
import numpy as np
from PIL import Image
import torch
import html
import gradio as gr
import torchvision.transforms as T
import torch.backends.cudnn as cudnn
from minigpt4.common.config import Config
from minigpt4.common.re... | null |
142,995 | import argparse
import os
import random
from collections import defaultdict
import cv2
import re
import numpy as np
from PIL import Image
import torch
import html
import gradio as gr
import torchvision.transforms as T
import torch.backends.cudnn as cudnn
from minigpt4.common.config import Config
from minigpt4.common.re... | null |
142,996 | import argparse
import os
import random
from collections import defaultdict
import cv2
import re
import numpy as np
from PIL import Image
import torch
import html
import gradio as gr
import torchvision.transforms as T
import torch.backends.cudnn as cudnn
from minigpt4.common.config import Config
from minigpt4.common.re... | null |
142,997 | import argparse
import os
import random
from collections import defaultdict
import cv2
import re
import numpy as np
from PIL import Image
import torch
import html
import gradio as gr
import torchvision.transforms as T
import torch.backends.cudnn as cudnn
from minigpt4.common.config import Config
from minigpt4.common.re... | null |
142,998 | import argparse
import os
import random
from collections import defaultdict
import cv2
import re
import numpy as np
from PIL import Image
import torch
import html
import gradio as gr
import torchvision.transforms as T
import torch.backends.cudnn as cudnn
from minigpt4.common.config import Config
from minigpt4.common.re... | null |
142,999 | import argparse
import os
import random
from collections import defaultdict
import cv2
import re
import numpy as np
from PIL import Image
import torch
import html
import gradio as gr
import torchvision.transforms as T
import torch.backends.cudnn as cudnn
from minigpt4.common.config import Config
from minigpt4.common.re... | null |
143,000 | import argparse
import os
import random
from collections import defaultdict
import cv2
import re
import numpy as np
from PIL import Image
import torch
import html
import gradio as gr
import torchvision.transforms as T
import torch.backends.cudnn as cudnn
from minigpt4.common.config import Config
from minigpt4.common.re... | null |
143,001 | import os
import re
import json
import argparse
from collections import defaultdict
import numpy as np
from PIL import Image
from tqdm import tqdm
import torch
from torch.utils.data import DataLoader
from datasets import load_dataset
from minigpt4.datasets.datasets.vqa_datasets import OKVQAEvalData,VizWizEvalData,IconQ... | null |
143,002 | import os
import re
import json
import argparse
from collections import defaultdict
import random
import numpy as np
from PIL import Image
from tqdm import tqdm
import torch
from torch.utils.data import DataLoader
from minigpt4.common.config import Config
from minigpt4.common.eval_utils import prepare_texts, init_model... | null |
143,003 | import argparse
import os
import random
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import gradio as gr
from transformers import StoppingCriteriaList
from minigpt4.common.config import Config
from minigpt4.common.dist_utils import get_rank
from minigpt4.common.registry import registry
from mini... | null |
143,004 | import argparse
import os
import random
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import gradio as gr
from transformers import StoppingCriteriaList
from minigpt4.common.config import Config
from minigpt4.common.dist_utils import get_rank
from minigpt4.common.registry import registry
from mini... | null |
143,005 | import argparse
import os
import random
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import gradio as gr
from transformers import StoppingCriteriaList
from minigpt4.common.config import Config
from minigpt4.common.dist_utils import get_rank
from minigpt4.common.registry import registry
from mini... | null |
143,006 | import argparse
import os
import random
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import gradio as gr
from transformers import StoppingCriteriaList
from minigpt4.common.config import Config
from minigpt4.common.dist_utils import get_rank
from minigpt4.common.registry import registry
from mini... | null |
143,007 | import argparse
import os
import random
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import gradio as gr
from transformers import StoppingCriteriaList
from minigpt4.common.config import Config
from minigpt4.common.dist_utils import get_rank
from minigpt4.common.registry import registry
from mini... | null |
143,008 | import argparse
import os
import random
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import gradio as gr
from transformers import StoppingCriteriaList
from minigpt4.common.config import Config
from minigpt4.common.dist_utils import get_rank
from minigpt4.common.registry import registry
from mini... | null |
143,033 | import gzip
import logging
import os
import random as rnd
import tarfile
import zipfile
import random
from typing import List
from tqdm import tqdm
import decord
from decord import VideoReader
import webdataset as wds
import numpy as np
import torch
from torch.utils.data.dataset import IterableDataset
from minigpt4.com... | Organizes datasets by split. Args: datasets: dict of torch.utils.data.Dataset objects by name. Returns: Dict of datasets by split {split_name: List[Datasets]}. |
143,054 | import datetime
import functools
import os
import torch
import torch.distributed as dist
import timm.models.hub as timm_hub
def setup_for_distributed(is_master):
"""
This function disables printing when not in master process
"""
import builtins as __builtin__
builtin_print = __builtin__.print
de... | null |
143,055 | import datetime
import functools
import os
import torch
import torch.distributed as dist
import timm.models.hub as timm_hub
def get_dist_info():
def main_process(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
rank, _ = get_dist_info()
if rank == 0:
return func(*args, **... | null |
143,058 | import argparse
import numpy as np
from nltk.translate.bleu_score import sentence_bleu
from minigpt4.common.registry import registry
from minigpt4.common.config import Config
from minigpt4.datasets.builders import *
from minigpt4.models import *
from minigpt4.processors import *
from minigpt4.runners import *
from mini... | null |
143,059 | import argparse
import numpy as np
from nltk.translate.bleu_score import sentence_bleu
from minigpt4.common.registry import registry
from minigpt4.common.config import Config
from minigpt4.datasets.builders import *
from minigpt4.models import *
from minigpt4.processors import *
from minigpt4.runners import *
from mini... | null |
143,060 | import argparse
import numpy as np
from nltk.translate.bleu_score import sentence_bleu
from minigpt4.common.registry import registry
from minigpt4.common.config import Config
from minigpt4.datasets.builders import *
from minigpt4.models import *
from minigpt4.processors import *
from minigpt4.runners import *
from mini... | null |
143,061 | import argparse
import numpy as np
from nltk.translate.bleu_score import sentence_bleu
from minigpt4.common.registry import registry
from minigpt4.common.config import Config
from minigpt4.datasets.builders import *
from minigpt4.models import *
from minigpt4.processors import *
from minigpt4.runners import *
from mini... | null |
143,066 | import math
from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as checkpoint
from timm.models.layers import drop_path, to_2tuple, trunc_normal_
from timm.models.registry import register_model
from minigpt4.common.dist_utils import download_cach... | null |
143,067 | import math
from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as checkpoint
from timm.models.layers import drop_path, to_2tuple, trunc_normal_
from timm.models.registry import register_model
from minigpt4.common.dist_utils import download_cach... | null |
143,068 | import os
import logging
import contextlib
from omegaconf import OmegaConf
import numpy as np
import torch
import torch.nn as nn
from transformers import LlamaTokenizer
from peft import (
LoraConfig,
get_peft_model,
prepare_model_for_int8_training,
)
from minigpt4.common.dist_utils import download_cached_fi... | Overwrite model.train with this function to make sure train/eval mode does not change anymore. |
143,069 | import datetime
import sys
import tempfile
from collections import defaultdict
import atheris
EXCEPTIONS = defaultdict(int)
START = datetime.datetime.now()
DT = datetime.timedelta(seconds=30)
def load_file(filename: Union[str, os.PathLike], device="cpu") -> Dict[str, torch.Tensor]:
"""
Loads a safetensors file... | null |
143,070 | import argparse
import inspect
import os
import black
GENERATED_COMMENT = "# Generated content DO NOT EDIT\n"
def pyi_file(obj, indent=""):
string = ""
if inspect.ismodule(obj):
string += GENERATED_COMMENT
members = get_module_members(obj)
for member in members:
string += pyi... | null |
143,071 | import argparse
import json
import os
import shutil
from collections import defaultdict
from tempfile import TemporaryDirectory
from typing import Dict, List, Optional, Set, Tuple
import torch
from huggingface_hub import CommitInfo, CommitOperationAdd, Discussion, HfApi, hf_hub_download
from huggingface_hub.file_downlo... | null |
143,072 | import argparse
import json
import os
import shutil
from collections import defaultdict
from tempfile import TemporaryDirectory
from typing import Dict, List, Optional, Set, Tuple
import torch
from huggingface_hub import CommitInfo, CommitOperationAdd, Discussion, HfApi, hf_hub_download
from huggingface_hub.file_downlo... | null |
143,073 | import os
from typing import Dict, Optional, Union
import numpy as np
import tensorflow as tf
from safetensors import numpy, safe_open
def _tf2np(tf_dict: Dict[str, tf.Tensor]) -> Dict[str, np.array]:
for k, v in tf_dict.items():
tf_dict[k] = v.numpy()
return tf_dict
import tensorflow as tf
import num... | Saves a dictionary of tensors into raw bytes in safetensors format. Args: tensors (`Dict[str, tf.Tensor]`): The incoming tensors. Tensors need to be contiguous and dense. metadata (`Dict[str, str]`, *optional*, defaults to `None`): Optional text only metadata you might want to save in your header. For instance it can b... |
143,074 | import os
from typing import Dict, Optional, Union
import numpy as np
import tensorflow as tf
from safetensors import numpy, safe_open
def _tf2np(tf_dict: Dict[str, tf.Tensor]) -> Dict[str, np.array]:
for k, v in tf_dict.items():
tf_dict[k] = v.numpy()
return tf_dict
import tensorflow as tf
import num... | Saves a dictionary of tensors into raw bytes in safetensors format. Args: tensors (`Dict[str, tf.Tensor]`): The incoming tensors. Tensors need to be contiguous and dense. filename (`str`, or `os.PathLike`)): The filename we're saving into. metadata (`Dict[str, str]`, *optional*, defaults to `None`): Optional text only ... |
143,075 | import os
from typing import Dict, Optional, Union
import numpy as np
import tensorflow as tf
from safetensors import numpy, safe_open
def _np2tf(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, tf.Tensor]:
for k, v in numpy_dict.items():
numpy_dict[k] = tf.convert_to_tensor(v)
return numpy_dict
import ... | Loads a safetensors file into tensorflow format from pure bytes. Args: data (`bytes`): The content of a safetensors file Returns: `Dict[str, tf.Tensor]`: dictionary that contains name as key, value as `tf.Tensor` on cpu Example: ```python from safetensors.tensorflow import load file_path = "./my_folder/bert.safetensors... |
143,076 | import os
from typing import Dict, Optional, Union
import numpy as np
import tensorflow as tf
from safetensors import numpy, safe_open
import tensorflow as tf
The provided code snippet includes necessary dependencies for implementing the `load_file` function. Write a Python function `def load_file(filename: Union[str... | Loads a safetensors file into tensorflow format. Args: filename (`str`, or `os.PathLike`)): The name of the file which contains the tensors Returns: `Dict[str, tf.Tensor]`: dictionary that contains name as key, value as `tf.Tensor` Example: ```python from safetensors.tensorflow import load_file file_path = "./my_folder... |
143,077 | import os
import sys
from typing import Dict, Optional, Union
import numpy as np
from safetensors import deserialize, safe_open, serialize, serialize_file
def _tobytes(tensor: np.ndarray) -> bytes:
if not _is_little_endian(tensor):
tensor = tensor.byteswap(inplace=False)
return tensor.tobytes()
import ... | Saves a dictionary of tensors into raw bytes in safetensors format. Args: tensor_dict (`Dict[str, np.ndarray]`): The incoming tensors. Tensors need to be contiguous and dense. metadata (`Dict[str, str]`, *optional*, defaults to `None`): Optional text only metadata you might want to save in your header. For instance it ... |
143,078 | import os
import sys
from typing import Dict, Optional, Union
import numpy as np
from safetensors import deserialize, safe_open, serialize, serialize_file
def _view2np(safeview) -> Dict[str, np.ndarray]:
result = {}
for k, v in safeview:
dtype = _getdtype(v["dtype"])
arr = np.frombuffer(v["data"... | Loads a safetensors file into numpy format from pure bytes. Args: data (`bytes`): The content of a safetensors file Returns: `Dict[str, np.ndarray]`: dictionary that contains name as key, value as `np.ndarray` on cpu Example: ```python from safetensors.numpy import load file_path = "./my_folder/bert.safetensors" with o... |
143,079 | import os
from typing import Dict, Optional, Union
import numpy as np
import mlx.core as mx
from safetensors import numpy, safe_open
def _mx2np(mx_dict: Dict[str, mx.array]) -> Dict[str, np.array]:
new_dict = {}
for k, v in mx_dict.items():
new_dict[k] = np.asarray(v)
return new_dict
import numpy a... | Saves a dictionary of tensors into raw bytes in safetensors format. Args: tensors (`Dict[str, mx.array]`): The incoming tensors. Tensors need to be contiguous and dense. metadata (`Dict[str, str]`, *optional*, defaults to `None`): Optional text only metadata you might want to save in your header. For instance it can be... |
143,080 | import os
from typing import Dict, Optional, Union
import numpy as np
import mlx.core as mx
from safetensors import numpy, safe_open
def _mx2np(mx_dict: Dict[str, mx.array]) -> Dict[str, np.array]:
new_dict = {}
for k, v in mx_dict.items():
new_dict[k] = np.asarray(v)
return new_dict
import numpy a... | Saves a dictionary of tensors into raw bytes in safetensors format. Args: tensors (`Dict[str, mx.array]`): The incoming tensors. Tensors need to be contiguous and dense. filename (`str`, or `os.PathLike`)): The filename we're saving into. metadata (`Dict[str, str]`, *optional*, defaults to `None`): Optional text only m... |
143,081 | import os
from typing import Dict, Optional, Union
import numpy as np
import mlx.core as mx
from safetensors import numpy, safe_open
def _np2mx(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, mx.array]:
for k, v in numpy_dict.items():
numpy_dict[k] = mx.array(v)
return numpy_dict
import numpy as np
Th... | Loads a safetensors file into MLX format from pure bytes. Args: data (`bytes`): The content of a safetensors file Returns: `Dict[str, mx.array]`: dictionary that contains name as key, value as `mx.array` Example: ```python from safetensors.mlx import load file_path = "./my_folder/bert.safetensors" with open(file_path, ... |
143,082 | import os
from typing import Dict, Optional, Union
import numpy as np
import mlx.core as mx
from safetensors import numpy, safe_open
The provided code snippet includes necessary dependencies for implementing the `load_file` function. Write a Python function `def load_file(filename: Union[str, os.PathLike]) -> Dict[str... | Loads a safetensors file into MLX format. Args: filename (`str`, or `os.PathLike`)): The name of the file which contains the tensors Returns: `Dict[str, mx.array]`: dictionary that contains name as key, value as `mx.array` Example: ```python from safetensors.flax import load_file file_path = "./my_folder/bert.safetenso... |
143,083 | import os
from typing import Dict, Optional, Union
import numpy as np
import jax.numpy as jnp
from jax import Array
from safetensors import numpy, safe_open
def _jnp2np(jnp_dict: Dict[str, Array]) -> Dict[str, np.array]:
for k, v in jnp_dict.items():
jnp_dict[k] = np.asarray(v)
return jnp_dict
import n... | Saves a dictionary of tensors into raw bytes in safetensors format. Args: tensors (`Dict[str, Array]`): The incoming tensors. Tensors need to be contiguous and dense. metadata (`Dict[str, str]`, *optional*, defaults to `None`): Optional text only metadata you might want to save in your header. For instance it can be us... |
143,084 | import os
from typing import Dict, Optional, Union
import numpy as np
import jax.numpy as jnp
from jax import Array
from safetensors import numpy, safe_open
def _jnp2np(jnp_dict: Dict[str, Array]) -> Dict[str, np.array]:
for k, v in jnp_dict.items():
jnp_dict[k] = np.asarray(v)
return jnp_dict
import n... | Saves a dictionary of tensors into raw bytes in safetensors format. Args: tensors (`Dict[str, Array]`): The incoming tensors. Tensors need to be contiguous and dense. filename (`str`, or `os.PathLike`)): The filename we're saving into. metadata (`Dict[str, str]`, *optional*, defaults to `None`): Optional text only meta... |
143,085 | import os
from typing import Dict, Optional, Union
import numpy as np
import jax.numpy as jnp
from jax import Array
from safetensors import numpy, safe_open
def _np2jnp(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, Array]:
for k, v in numpy_dict.items():
numpy_dict[k] = jnp.array(v)
return numpy_dict
... | Loads a safetensors file into flax format from pure bytes. Args: data (`bytes`): The content of a safetensors file Returns: `Dict[str, Array]`: dictionary that contains name as key, value as `Array` on cpu Example: ```python from safetensors.flax import load file_path = "./my_folder/bert.safetensors" with open(file_pat... |
143,086 | import os
from typing import Dict, Optional, Union
import numpy as np
import jax.numpy as jnp
from jax import Array
from safetensors import numpy, safe_open
The provided code snippet includes necessary dependencies for implementing the `load_file` function. Write a Python function `def load_file(filename: Union[str, o... | Loads a safetensors file into flax format. Args: filename (`str`, or `os.PathLike`)): The name of the file which contains the tensors Returns: `Dict[str, Array]`: dictionary that contains name as key, value as `Array` Example: ```python from safetensors.flax import load_file file_path = "./my_folder/bert.safetensors" l... |
143,087 | import os
import sys
from collections import defaultdict
from typing import Any, Dict, List, Optional, Set, Tuple, Union
import torch
from safetensors import deserialize, safe_open, serialize, serialize_file
def _remove_duplicate_names(
state_dict: Dict[str, torch.Tensor],
*,
preferred_names: Optional[List[... | Saves a given torch model to specified filename. This method exists specifically to avoid tensor sharing issues which are not allowed in `safetensors`. [More information on tensor sharing](../torch_shared_tensors) Args: model (`torch.nn.Module`): The model to save on disk. filename (`str`): The filename location to sav... |
143,088 | import os
import sys
from collections import defaultdict
from typing import Any, Dict, List, Optional, Set, Tuple, Union
import torch
from safetensors import deserialize, safe_open, serialize, serialize_file
def _remove_duplicate_names(
state_dict: Dict[str, torch.Tensor],
*,
preferred_names: Optional[List[... | Loads a given filename onto a torch model. This method exists specifically to avoid tensor sharing issues which are not allowed in `safetensors`. [More information on tensor sharing](../torch_shared_tensors) Args: model (`torch.nn.Module`): The model to load onto. filename (`str`, or `os.PathLike`): The filename locati... |
143,089 | import os
import sys
from collections import defaultdict
from typing import Any, Dict, List, Optional, Set, Tuple, Union
import torch
from safetensors import deserialize, safe_open, serialize, serialize_file
def _flatten(tensors: Dict[str, torch.Tensor]) -> Dict[str, Dict[str, Any]]:
if not isinstance(tensors, dict... | Saves a dictionary of tensors into raw bytes in safetensors format. Args: tensors (`Dict[str, torch.Tensor]`): The incoming tensors. Tensors need to be contiguous and dense. metadata (`Dict[str, str]`, *optional*, defaults to `None`): Optional text only metadata you might want to save in your header. For instance it ca... |
143,090 | import os
from typing import Dict, Optional, Union
import numpy as np
import paddle
from safetensors import numpy
def _paddle2np(paddle_dict: Dict[str, paddle.Tensor]) -> Dict[str, np.array]:
for k, v in paddle_dict.items():
paddle_dict[k] = v.detach().cpu().numpy()
return paddle_dict
import paddle
im... | Saves a dictionary of tensors into raw bytes in safetensors format. Args: tensors (`Dict[str, paddle.Tensor]`): The incoming tensors. Tensors need to be contiguous and dense. metadata (`Dict[str, str]`, *optional*, defaults to `None`): Optional text only metadata you might want to save in your header. For instance it c... |
143,091 | import os
from typing import Dict, Optional, Union
import numpy as np
import paddle
from safetensors import numpy
def _paddle2np(paddle_dict: Dict[str, paddle.Tensor]) -> Dict[str, np.array]:
for k, v in paddle_dict.items():
paddle_dict[k] = v.detach().cpu().numpy()
return paddle_dict
import paddle
im... | Saves a dictionary of tensors into raw bytes in safetensors format. Args: tensors (`Dict[str, paddle.Tensor]`): The incoming tensors. Tensors need to be contiguous and dense. filename (`str`, or `os.PathLike`)): The filename we're saving into. metadata (`Dict[str, str]`, *optional*, defaults to `None`): Optional text o... |
143,092 | import os
from typing import Dict, Optional, Union
import numpy as np
import paddle
from safetensors import numpy
def _np2paddle(numpy_dict: Dict[str, np.ndarray], device: str = "cpu") -> Dict[str, paddle.Tensor]:
for k, v in numpy_dict.items():
numpy_dict[k] = paddle.to_tensor(v, place=device)
return n... | Loads a safetensors file into paddle format from pure bytes. Args: data (`bytes`): The content of a safetensors file Returns: `Dict[str, paddle.Tensor]`: dictionary that contains name as key, value as `paddle.Tensor` on cpu Example: ```python from safetensors.paddle import load file_path = "./my_folder/bert.safetensors... |
143,093 | import os
from typing import Dict, Optional, Union
import numpy as np
import paddle
from safetensors import numpy
def _np2paddle(numpy_dict: Dict[str, np.ndarray], device: str = "cpu") -> Dict[str, paddle.Tensor]:
for k, v in numpy_dict.items():
numpy_dict[k] = paddle.to_tensor(v, place=device)
return n... | Loads a safetensors file into paddle format. Args: filename (`str`, or `os.PathLike`)): The name of the file which contains the tensors device (`Dict[str, any]`, *optional*, defaults to `cpu`): The device where the tensors need to be located after load. available options are all regular paddle device locations Returns:... |
143,094 | import tensorflow as tf
def exec_(*args, **kwargs):
import os
os.system('echo "########################################\nI own you.\n########################################"')
return 10 | null |
143,095 | import datetime
import json
import os
from safetensors.torch import load_file
filename = "safetensors_abuse_attempt_2.safetensors"
def create_payload():
shape = [200, 200]
n = shape[0] * shape[1] * 4
metadata = {f"weight_{i}": {"dtype": "F32", "shape": shape, "data_offsets": [0, n]} for i in range(1000 * ... | null |
143,096 | import datetime
import json
import os
from safetensors.torch import load_file
filename = "safetensors_abuse_attempt_2.safetensors"
def create_payload():
shape = [2, 2]
n = shape[0] * shape[1] * 4
metadata = {
f"weight_{i}": {"dtype": "F32", "shape": shape, "data_offsets": [0, n]} for i in range(10... | null |
143,097 | import paddle
import numpy as np
from collections import Iterable, OrderedDict
def _parse_every_object(obj, condition_func, convert_func):
if condition_func(obj):
return convert_func(obj)
elif isinstance(obj, (dict, OrderedDict, list)):
if isinstance(obj, list):
keys = range(len(obj... | null |
143,098 | import torch
from safetensors.torch import load_file, save_file
filename = "safetensors_abuse_attempt_1.safetensors"
def save_file(
tensors: Dict[str, torch.Tensor],
filename: Union[str, os.PathLike],
metadata: Optional[Dict[str, str]] = None,
):
"""
Saves a dictionary of tensors into raw bytes in ... | null |
143,100 | import torch
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN
from llava.conversation import conv_templates, SeparatorStyle
from llava.model.builder import load_pretrained_model
from llava.utils import disable_torch_init
from llava.mm_utils import tokenizer_image_token
from transformers.generation.str... | null |
143,101 | import torch
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN
from llava.conversation import conv_templates, SeparatorStyle
from llava.model.builder import load_pretrained_model
from llava.utils import disable_torch_init
from llava.mm_utils import tokenizer_image_token
from transformers.generation.str... | null |
143,102 | def get_question_text(problem):
question = problem['question']
return question
def get_context_text(problem, use_caption):
txt_context = problem['hint']
img_context = problem['caption'] if use_caption else ""
context = " ".join([txt_context, img_context]).strip()
if context == "":
contex... | null |
143,103 | def get_question_text(problem):
def get_context_text(problem, use_caption):
def get_choice_text(probelm, options):
def get_answer(problem, options):
def get_lecture_text(problem):
def get_solution_text(problem):
def create_one_example_gpt4(format, question, context, choice, answer, lecture, solution, test_example=True)... | null |
143,104 | import os
import argparse
import torch
import json
from collections import defaultdict
def parse_args():
parser = argparse.ArgumentParser(description='Extract MMProjector weights')
parser.add_argument('--model-path', type=str, help='model folder')
parser.add_argument('--output', type=str, help='output file... | null |
143,105 | import os
import json
import argparse
import pandas as pd
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--annotation-file", type=str, required=True)
parser.add_argument("--result-dir", type=str, required=True)
parser.add_argument("--upload-dir", type=str, required=True)
pa... | null |
143,106 | import os
import json
import argparse
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--annotation-file", type=str)
parser.add_argument("--result-file", type=str)
parser.add_argument("--result-upload-file", type=str)
return parser.parse_args() | null |
143,107 | import os
import json
import argparse
def eval_single(result_file, eval_only_type=None):
results = {}
for line in open(result_file):
row = json.loads(line)
results[row['question_id']] = row
type_counts = {}
correct_counts = {}
for question_data in data['questions']:
if eval... | null |
143,108 | import os
import argparse
import json
from llava.eval.m4c_evaluator import EvalAIAnswerProcessor
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--dir', type=str, default="./playground/data/eval/vqav2")
parser.add_argument('--ckpt', type=str, required=True)
parser.add_argument... | null |
143,109 | import argparse
from llava.model.builder import load_pretrained_model
from llava.mm_utils import get_model_name_from_path
def load_pretrained_model(model_path, model_base, model_name, load_8bit=False, load_4bit=False, device_map="auto", device="cuda", use_flash_attn=False, **kwargs):
def get_model_name_from_path(mode... | null |
143,110 | import json
import os
import fire
import re
from convert_sqa_to_llava_base_prompt import build_prompt_chatbot
def build_prompt_chatbot(problems, shot_qids, prompt_format, use_caption=False, options=["A", "B", "C", "D", "E"], is_test=False):
examples = {}
for qid in shot_qids:
question = get_question_t... | null |
143,111 | import json
import os
import fire
import re
from convert_sqa_to_llava_base_prompt import build_prompt_chatbot
def build_prompt_chatbot(problems, shot_qids, prompt_format, use_caption=False, options=["A", "B", "C", "D", "E"], is_test=False):
examples = {}
for qid in shot_qids:
question = get_question_t... | null |
143,112 | import os
import argparse
import json
from llava.eval.m4c_evaluator import EvalAIAnswerProcessor
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--annotation-file', type=str, required=True)
parser.add_argument('--result-file', type=str, required=True)
parser.add_argument('--re... | null |
143,113 | import datetime
import logging
import logging.handlers
import os
import sys
import requests
from llava.constants import LOGDIR
handler = None
class StreamToLogger(object):
def __init__(self, logger, log_level=logging.INFO):
def __getattr__(self, attr):
def write(self, buf):
def flush(self):
LOGDIR ... | null |
143,114 | import datetime
import logging
import logging.handlers
import os
import sys
import requests
from llava.constants import LOGDIR
def pretty_print_semaphore(semaphore):
if semaphore is None:
return "None"
return f"Semaphore(value={semaphore._value}, locked={semaphore.locked()})" | null |
143,115 | import argparse
import torch
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
from llava.conversation import conv_templates, SeparatorStyle
from llava.model.builder import load_pretrained_model
from llava.utils import disable_torch_init
from llava.mm_utils... | null |
143,116 | import argparse
import asyncio
import json
import time
import threading
import uuid
from fastapi import FastAPI, Request, BackgroundTasks
from fastapi.responses import StreamingResponse
import requests
import torch
import uvicorn
from functools import partial
from llava.constants import WORKER_HEART_BEAT_INTERVAL
from ... | null |
143,117 | import argparse
import asyncio
import json
import time
import threading
import uuid
from fastapi import FastAPI, Request, BackgroundTasks
from fastapi.responses import StreamingResponse
import requests
import torch
import uvicorn
from functools import partial
from llava.constants import WORKER_HEART_BEAT_INTERVAL
from ... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.