id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
178,128 | import argparse
import itertools
import json
import os
import random
import time
from functools import partial
from typing import Optional
import torch
from tqdm import tqdm
from PIL import Image
import pandas as pd
import re
from mplug_owl2.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN
from mplug_owl2.conver... | Parse the prediction from the generated response. Return the predicted index e.g., A, B, C, D. |
178,129 | import argparse
import itertools
import json
import os
import random
import time
from functools import partial
from typing import Optional
import torch
from tqdm import tqdm
from PIL import Image
import pandas as pd
import re
from mplug_owl2.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN
from mplug_owl2.conver... | Parse the prediction from the generated response. Return a list of predicted strings or numbers. |
178,130 | import argparse
import itertools
import json
import os
import random
import time
from functools import partial
from typing import Optional
import torch
from tqdm import tqdm
from PIL import Image
import pandas as pd
import re
from mplug_owl2.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN
from mplug_owl2.conver... | Batch evaluation for multiple choice and open questions. |
178,131 | import argparse
import itertools
import json
import os
import random
import time
from functools import partial
from typing import Optional
import torch
from tqdm import tqdm
from PIL import Image
import pandas as pd
import re
from mplug_owl2.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN
from mplug_owl2.conver... | null |
178,132 | import datetime
import logging
import logging.handlers
import os
import sys
import requests
from mplug_owl2.constants import LOGDIR
handler = None
class StreamToLogger(object):
"""
Fake file-like stream object that redirects writes to a logger instance.
"""
def __init__(self, logger, log_level=logging.I... | null |
178,133 | import datetime
import logging
import logging.handlers
import os
import sys
import requests
from mplug_owl2.constants import LOGDIR
The provided code snippet includes necessary dependencies for implementing the `disable_torch_init` function. Write a Python function `def disable_torch_init()` to solve the following pro... | Disable the redundant torch default initialization to accelerate model creation. |
178,134 | import datetime
import logging
import logging.handlers
import os
import sys
import requests
from mplug_owl2.constants import LOGDIR
def pretty_print_semaphore(semaphore):
if semaphore is None:
return "None"
return f"Semaphore(value={semaphore._value}, locked={semaphore.locked()})" | null |
178,135 | import argparse
import torch
from mplug_owl2.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN
from mplug_owl2.conversation import conv_templates, SeparatorStyle
from mplug_owl2.model.builder import load_pretrained_model
from mplug_owl2.mm_utils import process_images, tokenizer_image_token, get_model_name_from_pa... | Disable the redundant torch default initialization to accelerate model creation. |
178,136 | import argparse
import torch
from mplug_owl2.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN
from mplug_owl2.conversation import conv_templates, SeparatorStyle
from mplug_owl2.model.builder import load_pretrained_model
from mplug_owl2.mm_utils import process_images, tokenizer_image_token, get_model_name_from_pa... | null |
178,137 | 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 mplug_owl2.constants import WORKER_HEART_BEAT_INTERVAL
... | null |
178,138 | 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 mplug_owl2.constants import WORKER_HEART_BEAT_INTERVAL
... | null |
178,139 | 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 mplug_owl2.constants import WORKER_HEART_BEAT_INTERVAL
... | null |
178,140 | import argparse
import asyncio
import dataclasses
from enum import Enum, auto
import json
import logging
import time
from typing import List, Union
import threading
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
import numpy as np
import requests
import uvicorn
from mplug_owl2.cons... | null |
178,141 | import argparse
import asyncio
import dataclasses
from enum import Enum, auto
import json
import logging
import time
from typing import List, Union
import threading
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
import numpy as np
import requests
import uvicorn
from mplug_owl2.cons... | null |
178,142 | import argparse
import asyncio
import dataclasses
from enum import Enum, auto
import json
import logging
import time
from typing import List, Union
import threading
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
import numpy as np
import requests
import uvicorn
from mplug_owl2.cons... | null |
178,143 | import argparse
import asyncio
import dataclasses
from enum import Enum, auto
import json
import logging
import time
from typing import List, Union
import threading
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
import numpy as np
import requests
import uvicorn
from mplug_owl2.cons... | null |
178,144 | import argparse
import asyncio
import dataclasses
from enum import Enum, auto
import json
import logging
import time
from typing import List, Union
import threading
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
import numpy as np
import requests
import uvicorn
from mplug_owl2.cons... | null |
178,145 | import argparse
import asyncio
import dataclasses
from enum import Enum, auto
import json
import logging
import time
from typing import List, Union
import threading
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
import numpy as np
import requests
import uvicorn
from mplug_owl2.cons... | null |
178,146 | import argparse
import asyncio
import dataclasses
from enum import Enum, auto
import json
import logging
import time
from typing import List, Union
import threading
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
import numpy as np
import requests
import uvicorn
from mplug_owl2.cons... | null |
178,147 | import argparse
import asyncio
import dataclasses
from enum import Enum, auto
import json
import logging
import time
from typing import List, Union
import threading
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
import numpy as np
import requests
import uvicorn
from mplug_owl2.cons... | null |
178,148 | import argparse
import datetime
import json
import os
import time
import gradio as gr
import requests
from mplug_owl2.conversation import (default_conversation, conv_templates,
SeparatorStyle)
from mplug_owl2.constants import LOGDIR
from mplug_owl2.utils import (build_logger, server_e... | null |
178,149 | import os
import copy
from dataclasses import dataclass, field
import json
import logging
import pathlib
from typing import Dict, Optional, Sequence, List
import torch
import transformers
from transformers.models.clip.image_processing_clip import CLIPImageProcessor
from torch.utils.data import Dataset
from mplug_owl2.t... | null |
178,150 | import os
import copy
from dataclasses import dataclass, field
import json
import logging
import pathlib
from typing import Dict, Optional, Sequence, List
import torch
import transformers
from transformers.models.clip.image_processing_clip import CLIPImageProcessor
from torch.utils.data import Dataset
from mplug_owl2.t... | Resize tokenizer and embedding. Note: This is the unoptimized version that may make your embedding size not be divisible by 64. |
178,151 | import os
import copy
from dataclasses import dataclass, field
import json
import logging
import pathlib
from typing import Dict, Optional, Sequence, List
import torch
import transformers
from transformers.models.clip.image_processing_clip import CLIPImageProcessor
from torch.utils.data import Dataset
from mplug_owl2.t... | null |
178,152 | import os
import copy
from dataclasses import dataclass, field
import json
import logging
import pathlib
from typing import Dict, Optional, Sequence, List
import torch
import transformers
from transformers.models.clip.image_processing_clip import CLIPImageProcessor
from torch.utils.data import Dataset
from mplug_owl2.t... | Given a list of sources, each is a conversation list. This transform: 1. Add signal '### ' at the beginning each sentence, with end signal '\n'; 2. Concatenate conversations together; 3. Tokenize the concatenated conversation; 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX. |
178,153 | import os
import copy
from dataclasses import dataclass, field
import json
import logging
import pathlib
from typing import Dict, Optional, Sequence, List
import torch
import transformers
from transformers.models.clip.image_processing_clip import CLIPImageProcessor
from torch.utils.data import Dataset
from mplug_owl2.t... | null |
178,154 | from typing import Optional, Tuple
import warnings
import torch
import transformers
from transformers.models.llama.modeling_llama import apply_rotary_pos_emb, repeat_kv
from flash_attn.bert_padding import unpad_input, pad_input
def forward(
self,
hidden_states: torch.Tensor,
modality_indicators: torch.Tenso... | null |
178,155 | import os
import torch
from torch.utils.data import Sampler
from transformers import Trainer
from transformers.trainer import (
is_sagemaker_mp_enabled,
get_parameter_names,
has_length,
ALL_LAYERNORM_LAYERS,
ShardedDDPOption,
logger,
)
from typing import List, Optional
from icecream import ic
de... | null |
178,156 | import os
import torch
from torch.utils.data import Sampler
from transformers import Trainer
from transformers.trainer import (
is_sagemaker_mp_enabled,
get_parameter_names,
has_length,
ALL_LAYERNORM_LAYERS,
ShardedDDPOption,
logger,
)
from typing import List, Optional
from icecream import ic
de... | null |
178,157 | import argparse
import datetime
import json
import os
import time
import gradio as gr
import requests
from mplug_owl2.conversation import (default_conversation, conv_templates,
SeparatorStyle)
from mplug_owl2.constants import LOGDIR
from mplug_owl2.utils import (build_logger, server_e... | null |
178,158 | from PIL import Image
from io import BytesIO
import base64
import torch
from transformers import StoppingCriteria
from mplug_owl2.constants import IMAGE_TOKEN_INDEX,DEFAULT_IMAGE_TOKEN
from icecream import ic
def load_image_from_base64(image):
return Image.open(BytesIO(base64.b64decode(image))) | null |
178,159 | from PIL import Image
from io import BytesIO
import base64
import torch
from transformers import StoppingCriteria
from mplug_owl2.constants import IMAGE_TOKEN_INDEX,DEFAULT_IMAGE_TOKEN
from icecream import ic
def expand2square(pil_img, background_color):
width, height = pil_img.size
if width == height:
... | null |
178,160 | from PIL import Image
from io import BytesIO
import base64
import torch
from transformers import StoppingCriteria
from mplug_owl2.constants import IMAGE_TOKEN_INDEX,DEFAULT_IMAGE_TOKEN
from icecream import ic
def get_model_name_from_path(model_path):
model_path = model_path.strip("/")
model_paths = model_path.... | null |
178,161 | import argparse
import gc
import json
import math
import os
import shutil
import warnings
import torch
from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer
from .configuration_mplug_owl2 import MPLUGOwl2Config, MplugOwlVisionConfig, MplugOwlVisualAbstractorConfig
from .modeling_mplug_owl2 import MPLUG... | null |
178,162 | import argparse
import gc
import json
import math
import os
import shutil
import warnings
import torch
from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer
from .configuration_mplug_owl2 import MPLUGOwl2Config, MplugOwlVisionConfig, MplugOwlVisualAbstractorConfig
from .modeling_mplug_owl2 import MPLUG... | null |
178,163 | import argparse
import gc
import json
import math
import os
import shutil
import warnings
import torch
from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer
from .configuration_mplug_owl2 import MPLUGOwl2Config, MplugOwlVisionConfig, MplugOwlVisualAbstractorConfig
from .modeling_mplug_owl2 import MPLUG... | null |
178,164 | import argparse
import gc
import json
import math
import os
import shutil
import warnings
import torch
from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer
from .configuration_mplug_owl2 import MPLUGOwl2Config, MplugOwlVisionConfig, MplugOwlVisualAbstractorConfig
from .modeling_mplug_owl2 import MPLUG... | null |
178,165 | import copy
from functools import partial
import importlib
import math
import pathlib
from typing import TYPE_CHECKING, Optional, Tuple, Union, Callable, List, Any, Generator
import torch
import torch.nn.functional as F
import torch.utils.checkpoint
import warnings
from torch.nn import CrossEntropyLoss
from transformer... | null |
178,166 | import copy
from functools import partial
import importlib
import math
import pathlib
from typing import TYPE_CHECKING, Optional, Tuple, Union, Callable, List, Any, Generator
import torch
import torch.nn.functional as F
import torch.utils.checkpoint
import warnings
from torch.nn import CrossEntropyLoss
from transformer... | null |
178,167 | import copy
from functools import partial
import importlib
import math
import pathlib
from typing import TYPE_CHECKING, Optional, Tuple, Union, Callable, List, Any, Generator
import torch
import torch.nn.functional as F
import torch.utils.checkpoint
import warnings
from torch.nn import CrossEntropyLoss
from transformer... | null |
178,168 | import copy
from functools import partial
import importlib
import math
import pathlib
from typing import TYPE_CHECKING, Optional, Tuple, Union, Callable, List, Any, Generator
import torch
import torch.nn.functional as F
import torch.utils.checkpoint
import warnings
from torch.nn import CrossEntropyLoss
from transformer... | Apply rotary embedding to the first rotary_dim of the iput Arguments: t (tensor(batch_size, seq_len, n_head, head_dim)): the input embedding/hidden states freqs (list[tensor(1, seq_len, 1, rotary_dim), tensor(1, seq_len, 1, rotary_dim)]): the cached cos/sin position embeddings |
178,169 | from transformers import AutoConfig
def auto_upgrade(config):
cfg = AutoConfig.from_pretrained(config)
if 'mplug_owl2' in config and 'mplug_owl2' not in cfg.model_type:
assert cfg.model_type == 'mplug_owl2'
print("You are using newer LLaVA code base, while the checkpoint of v0 is from older cod... | null |
178,170 | import inspect
import math
import warnings
from functools import partial
from typing import List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
import torch.utils.checkpoint
from torch import nn
import transformers
from transformers.models.llama.modeling_llama import *
from transformers.configurat... | This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) |
178,171 | import inspect
import math
import warnings
from functools import partial
from typing import List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
import torch.utils.checkpoint
from torch import nn
import transformers
from transformers.models.llama.modeling_llama import *
from transformers.configurat... | null |
178,172 | from typing import List, Optional, Tuple, Union
import torch
class AttentionMaskConverter:
"""
A utility attention mask class that allows one to:
- Create a causal 4d mask
- Create a causal 4d mask with slided window
- Convert a 2d attention mask (batch_size, query_length) to a 4d attent... | Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape `(batch_size, key_value_length)` Args: attention_mask (`torch.Tensor` or `None`): A 2D attention mask of shape `(batch_size, key_value_length)` input_shape (`tuple(int)` or `list(int)` or `torch.Size`): The input... |
178,173 | from typing import List, Optional, Tuple, Union
import torch
class AttentionMaskConverter:
"""
A utility attention mask class that allows one to:
- Create a causal 4d mask
- Create a causal 4d mask with slided window
- Convert a 2d attention mask (batch_size, query_length) to a 4d attent... | Creates a non-causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape `(batch_size, key_value_length)` Args: mask (`torch.Tensor` or `None`): A 2D attention mask of shape `(batch_size, key_value_length)` dtype (`torch.dtype`): The torch dtype the created mask shall have. tgt_le... |
178,174 | from typing import List, Optional, Tuple, Union
import torch
class AttentionMaskConverter:
"""
A utility attention mask class that allows one to:
- Create a causal 4d mask
- Create a causal 4d mask with slided window
- Convert a 2d attention mask (batch_size, query_length) to a 4d attent... | Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` Args: input_shape (`tuple(int)` or `list(int)` or `torch.Size`): The input shape should be a tuple that defines `(batch_size, query_length)`. dtype (`torch.dtype`): The torch dtype the created mask shall have. device (`int`): The torch ... |
178,175 | import os
import warnings
import shutil
from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig, BitsAndBytesConfig
from transformers.models.clip.image_processing_clip import CLIPImageProcessor
import torch
from mplug_owl2.model import *
from icecream import ic
def load_pretrained_model(model_path, mo... | null |
178,176 | import math
from typing import Any, Optional, Tuple, Union
from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, BaseModelOutputWithPastAndCrossAttentions
from transformers.modeling_utils import PreTrainedModel
from transformers.pytorch_utils import find_pruneable_heads_and_indices, pru... | null |
178,177 | import math
from typing import Any, Optional, Tuple, Union
from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, BaseModelOutputWithPastAndCrossAttentions
from transformers.modeling_utils import PreTrainedModel
from transformers.pytorch_utils import find_pruneable_heads_and_indices, pru... | grid_size: int of the grid height and width return: pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token) |
178,178 | from PIL import Image
import torch
import gradio as gr
import logging
import sys
import os
import json
import requests
from .conversation import default_conversation
from .gradio_patch import Chatbot as grChatbot
from .gradio_css import code_highlight_css
import datetime
import uuid
import base64
from io import BytesIO... | null |
178,179 | from PIL import Image
import torch
import gradio as gr
import logging
import sys
import os
import json
import requests
from .conversation import default_conversation
from .gradio_patch import Chatbot as grChatbot
from .gradio_css import code_highlight_css
import datetime
import uuid
import base64
from io import BytesIO... | null |
178,180 | from PIL import Image
import torch
import gradio as gr
import logging
import sys
import os
import json
import requests
from .conversation import default_conversation
from .gradio_patch import Chatbot as grChatbot
from .gradio_css import code_highlight_css
import datetime
import uuid
import base64
from io import BytesIO... | null |
178,181 | import re
import os
import sys
import shutil
import hashlib
from io import StringIO, BytesIO
from contextlib import contextmanager
from typing import List
from datetime import datetime, timedelta
def ignore_io_error(msg=''):
import oss2
try:
yield
except (oss2.exceptions.RequestError, oss2.exceptio... | null |
178,182 | import re
import os
import sys
import shutil
import hashlib
from io import StringIO, BytesIO
from contextlib import contextmanager
from typing import List
from datetime import datetime, timedelta
def mute_stderr():
cache = sys.stderr
sys.stderr = StringIO()
try:
yield None
finally:
sys.... | null |
178,184 | import argparse
import datetime
import json
import os
import time
import torch
import gradio as gr
import requests
from .conversation import default_conversation
from .gradio_css import code_highlight_css
from .gradio_patch import Chatbot as grChatbot
from .serve_utils import (
add_text, after_process_image, disabl... | null |
178,185 | import argparse
import datetime
import json
import os
import time
import torch
import gradio as gr
import requests
from .conversation import default_conversation
from .gradio_css import code_highlight_css
from .gradio_patch import Chatbot as grChatbot
from .serve_utils import (
add_text, after_process_image, disabl... | null |
178,186 | import logging
import math
from typing import Any, Optional, Tuple, Union
import math
from dataclasses import dataclass
from typing import Any, Optional, Tuple, Union
import torch
import torch.utils.checkpoint
from torch import nn
import einops
from transformers.modeling_outputs import (
BaseModelOutput,
BaseMo... | Build masks and position id for left to right model. |
178,187 | import logging
import math
from typing import Any, Optional, Tuple, Union
import math
from dataclasses import dataclass
from typing import Any, Optional, Tuple, Union
import torch
import torch.utils.checkpoint
from torch import nn
import einops
from transformers.modeling_outputs import (
BaseModelOutput,
BaseMo... | null |
178,188 | import logging
import math
from typing import Any, Optional, Tuple, Union
import math
from dataclasses import dataclass
from typing import Any, Optional, Tuple, Union
import torch
import torch.utils.checkpoint
from torch import nn
import einops
from transformers.modeling_outputs import (
BaseModelOutput,
BaseMo... | null |
178,189 | import logging
import math
from typing import Any, Optional, Tuple, Union
import math
from dataclasses import dataclass
from typing import Any, Optional, Tuple, Union
import torch
import torch.utils.checkpoint
from torch import nn
import einops
from transformers.modeling_outputs import (
BaseModelOutput,
BaseMo... | null |
178,190 | import re
import torch
import torch.utils.checkpoint
from transformers.processing_utils import ProcessorMixin
from transformers.tokenization_utils_base import BatchEncoding
from transformers.models.clip.image_processing_clip import CLIPImageProcessor
from .tokenization_mplug_owl import MplugOwlTokenizer
from decord imp... | null |
178,191 | import re
import torch
import torch.utils.checkpoint
from transformers.processing_utils import ProcessorMixin
from transformers.tokenization_utils_base import BatchEncoding
from transformers.models.clip.image_processing_clip import CLIPImageProcessor
from .tokenization_mplug_owl import MplugOwlTokenizer
from decord imp... | Detokenize the generated tokens. |
178,192 | import re
import torch
import torch.utils.checkpoint
from transformers.processing_utils import ProcessorMixin
from transformers.tokenization_utils_base import BatchEncoding
from transformers.models.clip.image_processing_clip import CLIPImageProcessor
from .tokenization_mplug_owl import MplugOwlTokenizer
from decord imp... | Tokenize prompts and make them avaiable on all ranks. |
178,193 | import math
import random
import torch
import numpy as np
from icecream import ic
from torch import distributed as dist
The provided code snippet includes necessary dependencies for implementing the `print_rank_0` function. Write a Python function `def print_rank_0(message)` to solve the following problem:
If distribu... | If distributed is initialized, print only on rank 0. |
178,194 | import math
import random
import torch
import numpy as np
from icecream import ic
ARGS = None
from torch import distributed as dist
def set_args(args):
global ARGS
ARGS = args | null |
178,195 | import math
import random
import torch
import numpy as np
from icecream import ic
ARGS = None
from torch import distributed as dist
def get_args():
return ARGS | null |
178,196 | import math
import random
import torch
import numpy as np
from icecream import ic
TOKENIZER = None
from torch import distributed as dist
def set_tokenizer(tokenizer):
global TOKENIZER
TOKENIZER = tokenizer | null |
178,197 | import math
import random
import torch
import numpy as np
from icecream import ic
TOKENIZER = None
from torch import distributed as dist
def get_tokenizer():
return TOKENIZER | null |
178,198 | import math
import random
import torch
import numpy as np
from icecream import ic
from torch import distributed as dist
def batchify(batch):
# collate_fn
# image = torch.cat([data["image"] for data in batch], dim=0)
image = [data["image"] if data["image"] is not None else None for data in batch]
if all... | null |
178,199 | import math
import random
import torch
import numpy as np
from icecream import ic
from torch import distributed as dist
The provided code snippet includes necessary dependencies for implementing the `get_param_groups` function. Write a Python function `def get_param_groups(modules, no_weight_decay... | creates param groups based on weight decay condition (regularized vs non regularized) and learning rate scale condition (args.lr vs lr_mult * args.lr) scale_lr_cond is used during finetuning where head of the network requires a scaled version of the base learning rate. |
178,200 | import math
import random
import torch
import numpy as np
from icecream import ic
from torch import distributed as dist
The provided code snippet includes necessary dependencies for implementing the `get_cosine_schedule_with_warmup` function. Write a Python function `def get_cosine_schedule_with_warmup( optimi... | Create a schedule with a learning rate that decreases following the values of the cosine function between the initial lr set in the optimizer to 0, after a warmup period during which it increases linearly between 0 and the initial lr set in the optimizer. Args: optimizer ([`~torch.optim.Optimizer`]): The optimizer for ... |
178,201 | import cv2
import numpy as np
from PIL import Image
def identity_func(img):
return img | null |
178,202 | import cv2
import numpy as np
from PIL import Image
The provided code snippet includes necessary dependencies for implementing the `autocontrast_func` function. Write a Python function `def autocontrast_func(img, cutoff=0)` to solve the following problem:
same output as PIL.ImageOps.autocontrast
Here is the function:... | same output as PIL.ImageOps.autocontrast |
178,203 | import cv2
import numpy as np
from PIL import Image
The provided code snippet includes necessary dependencies for implementing the `equalize_func` function. Write a Python function `def equalize_func(img)` to solve the following problem:
same output as PIL.ImageOps.equalize PIL's implementation is different from cv2.e... | same output as PIL.ImageOps.equalize PIL's implementation is different from cv2.equalize |
178,204 | import cv2
import numpy as np
from PIL import Image
The provided code snippet includes necessary dependencies for implementing the `rotate_func` function. Write a Python function `def rotate_func(img, degree, fill=(0, 0, 0))` to solve the following problem:
like PIL, rotate by degree, not radians
Here is the function... | like PIL, rotate by degree, not radians |
178,205 | import cv2
import numpy as np
from PIL import Image
The provided code snippet includes necessary dependencies for implementing the `solarize_func` function. Write a Python function `def solarize_func(img, thresh=128)` to solve the following problem:
same output as PIL.ImageOps.posterize
Here is the function:
def sol... | same output as PIL.ImageOps.posterize |
178,206 | import cv2
import numpy as np
from PIL import Image
The provided code snippet includes necessary dependencies for implementing the `color_func` function. Write a Python function `def color_func(img, factor)` to solve the following problem:
same output as PIL.ImageEnhance.Color
Here is the function:
def color_func(im... | same output as PIL.ImageEnhance.Color |
178,207 | import cv2
import numpy as np
from PIL import Image
The provided code snippet includes necessary dependencies for implementing the `contrast_func` function. Write a Python function `def contrast_func(img, factor)` to solve the following problem:
same output as PIL.ImageEnhance.Contrast
Here is the function:
def cont... | same output as PIL.ImageEnhance.Contrast |
178,208 | import cv2
import numpy as np
from PIL import Image
The provided code snippet includes necessary dependencies for implementing the `brightness_func` function. Write a Python function `def brightness_func(img, factor)` to solve the following problem:
same output as PIL.ImageEnhance.Contrast
Here is the function:
def ... | same output as PIL.ImageEnhance.Contrast |
178,209 | import cv2
import numpy as np
from PIL import Image
The provided code snippet includes necessary dependencies for implementing the `sharpness_func` function. Write a Python function `def sharpness_func(img, factor)` to solve the following problem:
The differences the this result and PIL are all on the 4 boundaries, th... | The differences the this result and PIL are all on the 4 boundaries, the center areas are same |
178,210 | import cv2
import numpy as np
from PIL import Image
def shear_x_func(img, factor, fill=(0, 0, 0)):
H, W = img.shape[0], img.shape[1]
M = np.float32([[1, factor, 0], [0, 1, 0]])
out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8)
return out | null |
178,211 | import cv2
import numpy as np
from PIL import Image
The provided code snippet includes necessary dependencies for implementing the `translate_x_func` function. Write a Python function `def translate_x_func(img, offset, fill=(0, 0, 0))` to solve the following problem:
same output as PIL.Image.transform
Here is the fun... | same output as PIL.Image.transform |
178,212 | import cv2
import numpy as np
from PIL import Image
The provided code snippet includes necessary dependencies for implementing the `translate_y_func` function. Write a Python function `def translate_y_func(img, offset, fill=(0, 0, 0))` to solve the following problem:
same output as PIL.Image.transform
Here is the fun... | same output as PIL.Image.transform |
178,213 | import cv2
import numpy as np
from PIL import Image
The provided code snippet includes necessary dependencies for implementing the `posterize_func` function. Write a Python function `def posterize_func(img, bits)` to solve the following problem:
same output as PIL.ImageOps.posterize
Here is the function:
def posteri... | same output as PIL.ImageOps.posterize |
178,214 | import cv2
import numpy as np
from PIL import Image
def shear_y_func(img, factor, fill=(0, 0, 0)):
H, W = img.shape[0], img.shape[1]
M = np.float32([[1, 0, 0], [factor, 1, 0]])
out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8)
return out | null |
178,215 | import cv2
import numpy as np
from PIL import Image
def cutout_func(img, pad_size, replace=(0, 0, 0)):
replace = np.array(replace, dtype=np.uint8)
H, W = img.shape[0], img.shape[1]
rh, rw = np.random.random(2)
pad_size = pad_size // 2
ch, cw = int(rh * H), int(rw * W)
x1, x2 = max(ch - pad_size... | null |
178,216 | import cv2
import numpy as np
from PIL import Image
def enhance_level_to_args(MAX_LEVEL):
def level_to_args(level):
return ((level / MAX_LEVEL) * 1.8 + 0.1,)
return level_to_args | null |
178,217 | import cv2
import numpy as np
from PIL import Image
def shear_level_to_args(MAX_LEVEL, replace_value):
def level_to_args(level):
level = (level / MAX_LEVEL) * 0.3
if np.random.random() > 0.5: level = -level
return (level, replace_value)
return level_to_args | null |
178,218 | import cv2
import numpy as np
from PIL import Image
def translate_level_to_args(translate_const, MAX_LEVEL, replace_value):
def level_to_args(level):
level = (level / MAX_LEVEL) * float(translate_const)
if np.random.random() > 0.5: level = -level
return (level, replace_value)
return le... | null |
178,219 | import cv2
import numpy as np
from PIL import Image
def cutout_level_to_args(cutout_const, MAX_LEVEL, replace_value):
def level_to_args(level):
level = int((level / MAX_LEVEL) * cutout_const)
return (level, replace_value)
return level_to_args | null |
178,220 | import cv2
import numpy as np
from PIL import Image
def solarize_level_to_args(MAX_LEVEL):
def level_to_args(level):
level = int((level / MAX_LEVEL) * 256)
return (level, )
return level_to_args | null |
178,221 | import cv2
import numpy as np
from PIL import Image
def none_level_to_args(level):
return () | null |
178,222 | import cv2
import numpy as np
from PIL import Image
def posterize_level_to_args(MAX_LEVEL):
def level_to_args(level):
level = int((level / MAX_LEVEL) * 4)
return (level, )
return level_to_args | null |
178,223 | import cv2
import numpy as np
from PIL import Image
def rotate_level_to_args(MAX_LEVEL, replace_value):
def level_to_args(level):
level = (level / MAX_LEVEL) * 30
if np.random.random() < 0.5:
level = -level
return (level, replace_value)
return level_to_args | null |
178,224 | import json
import logging
import os
import random
import re
import time
import traceback
import warnings
from io import BytesIO
import h5py
import numpy as np
import torch
from icecream import ic
from PIL import Image, ImageFile
from torch.utils.data import Dataset, Subset
from utils import get_args
from .processors i... | null |
178,225 | import inspect
import warnings
import functools
from functools import partial
from typing import Any, Dict, Optional
from collections import abc
from inspect import getfullargspec
The provided code snippet includes necessary dependencies for implementing the `is_seq_of` function. Write a Python function `def is_seq_of... | Check whether it is a sequence of some type. Args: seq (Sequence): The sequence to be checked. expected_type (type): Expected type of sequence items. seq_type (type, optional): Expected sequence type. Returns: bool: Whether the sequence is valid. |
178,226 | import inspect
import warnings
import functools
from functools import partial
from typing import Any, Dict, Optional
from collections import abc
from inspect import getfullargspec
The provided code snippet includes necessary dependencies for implementing the `deprecated_api_warning` function. Write a Python function `... | A decorator to check if some arguments are deprecate and try to replace deprecate src_arg_name to dst_arg_name. Args: name_dict(dict): key (str): Deprecate argument names. val (str): Expected argument names. Returns: func: New function. |
178,227 | import os
import numpy as np
from data_utils.registry import Registry, build_from_cfg
PROCESSORS = Registry('processors')
def build_from_cfg(cfg: Dict,
registry: 'Registry',
default_args: Optional[Dict] = None) -> Any:
"""Build a module from config dict when it is a class conf... | null |
178,228 | import torch
import numpy as np
import requests
from PIL import Image
from mplug_owl.modeling_mplug_owl import MplugOwlForConditionalGeneration
from mplug_owl.processing_mplug_owl import MplugOwlImageProcessor, MplugOwlProcessor
from transformers import AutoTokenizer
)
)
class MplugOwlForConditionalGeneration(MplugO... | Model Provider with tokenizer and processor. Args: pretrained_ckpt (string): The path to pre-trained checkpoint. use_bf16 (bool, optional): Whether to use bfloat16 to load the model. Defaults to False. Returns: model: MplugOwl Model tokenizer: MplugOwl text tokenizer processor: MplugOwl processor (including text and im... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.