index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9,602 | /home/hieuvd/dung_repo/raw/stars_01/automl_auto-sklearn/auto-sklearn | /home/hieuvd/dung_repo/raw/stars_01/automl_auto-sklearn/auto-sklearn/autosklearn/util/dependencies.py | 11,12 | 1,106 | verify_packages | 12,36 | 12,36 | from typing import List, Optional, Union, no_type_check
import importlib
from distutils.version import LooseVersion
import pkg_resources
from autosklearn.util import RE_PATTERN
def verify_packages(packages: Optional[Union[str, List[str]]]) -> None:
FILL_FUNC_BODY@no_type_check
def _verify_package(name: str, operat... | from typing import List, Optional, Union, no_type_check
import importlib
from distutils.version import LooseVersion
import pkg_resources
from autosklearn.util import RE_PATTERN
def verify_packages(packages: Optional[Union[str, List[str]]]) -> None:
FILL_FUNC_BODY@no_type_check
def _verify_package(name: str, operat... | if not packages:
return
if isinstance(packages, str):
packages = packages.splitlines()
for package in packages:
if not package:
continue
# Ignore comments
if package.startswith("#"):
continue
match = RE_PATTERN.match(package)
... | if not packages:
return
if isinstance(packages, str):
packages = packages.splitlines()
for package in packages:
if not package:
continue
# Ignore comments
if package.startswith("#"):
continue
match = RE_PATTERN.match(package)
... | 57 | 698 | 190 | 888 | from typing import List, Optional, Union, no_type_check
import importlib
from distutils.version import LooseVersion
import pkg_resources
from autosklearn.util import RE_PATTERN
def verify_packages(packages: Optional[Union[str, List[str]]]) -> None:
FILL_FUNC_BODY@no_type_check
def _verify_package(name: str, operat... | from typing import List, Optional, Union, no_type_check
import importlib
from distutils.version import LooseVersion
import pkg_resources
from autosklearn.util import RE_PATTERN
def verify_packages(packages: Optional[Union[str, List[str]]]) -> None:
FILL_FUNC_BODY@no_type_check
def _verify_package(name: str, operat... | |
9,603 | /home/hieuvd/dung_repo/raw/stars_01/automl_auto-sklearn/auto-sklearn | /home/hieuvd/dung_repo/raw/stars_01/automl_auto-sklearn/auto-sklearn/autosklearn/util/disk.py | 51,58 | 1,104 | rmtree | 85,104 | 58,104 | from __future__ import annotations
from typing import Any
import math
import shutil
import tempfile
import uuid
from pathlib import Path
sizes = {
"B": 0,
"KB": 1,
"MB": 2,
"GB": 3,
"TB": 4,
}
def sizeof(path: Path | str, unit: str = "B") -> float:
"""Get the size of some path object
P... | from __future__ import annotations
from typing import Any
import math
import shutil
import tempfile
import uuid
from pathlib import Path
sizes = {
"B": 0,
"KB": 1,
"MB": 2,
"GB": 3,
"TB": 4,
}
def sizeof(path: Path | str, unit: str = "B") -> float:
"""Get the size of some path object
P... | if isinstance(path, str):
path = Path(path)
if atomic:
if tmp is True:
dir = Path(tempfile.gettempdir())
uid = uuid.uuid4()
mvpath = dir / f"autosklearn-{path.name}.old_{uid}"
elif tmp is False:
uid = uuid.uuid4()
mvpath = pat... | """Delete a file or directory
Parameters
----------
path: Path | str
The path to delete
atomic: bool = False
Whether to delete the file/folder atomically. This is done by first
using a `move` before `rmtree`.
The `move` is not guaranteed to be atomic if moving betw... | 51 | 627 | 210 | 837 | from __future__ import annotations
from typing import Any
import math
import shutil
import tempfile
import uuid
from pathlib import Path
sizes = {
"B": 0,
"KB": 1,
"MB": 2,
"GB": 3,
"TB": 4,
}
def sizeof(path: Path | str, unit: str = "B") -> float:
"""Get the size of some path object
P... | from __future__ import annotations
from typing import Any
import math
import shutil
import tempfile
import uuid
from pathlib import Path
sizes = {
"B": 0,
"KB": 1,
"MB": 2,
"GB": 3,
"TB": 4,
}
def sizeof(path: Path | str, unit: str = "B") -> float:
"""Get the size of some path object
P... | |
9,604 | /home/hieuvd/dung_repo/raw/stars_01/automl_auto-sklearn/auto-sklearn | /home/hieuvd/dung_repo/raw/stars_01/automl_auto-sklearn/auto-sklearn/autosklearn/util/functional.py | 11,12 | 1,258 | intersection | 31,37 | 12,37 | from __future__ import annotations
from typing import Callable, Hashable, Iterable, Iterator, TypeVar
from functools import reduce
from itertools import chain, cycle, islice, tee
T = TypeVar("T")
def intersection(*items: Iterable[T]) -> set[T]:
FILL_FUNC_BODYdef cut(
itr: Iterable[T],
where: int | Callable... | from __future__ import annotations
from typing import Callable, Hashable, Iterable, Iterator, TypeVar
from functools import reduce
from itertools import chain, cycle, islice, tee
T = TypeVar("T")
def intersection(*items: Iterable[T]) -> set[T]:
"""Does an intersection over all collection of items
..code::... | if len(items) == 0:
return set()
return set(reduce(lambda s1, s2: set(s1) & set(s2), items, items[0]))
| """Does an intersection over all collection of items
..code:: python
ans = intersection(["a", "b", "c"], "ab", ("b", "c"))
items = [(1, 2, 3), (2, 3), (4, 5)]
ans = intesection(*items)
Parameters
----------
*items : Iterable[T]
A list of lists
Returns
---... | 15 | 1,861 | 56 | 1,917 | from __future__ import annotations
from typing import Callable, Hashable, Iterable, Iterator, TypeVar
from functools import reduce
from itertools import chain, cycle, islice, tee
T = TypeVar("T")
def intersection(*items: Iterable[T]) -> set[T]:
FILL_FUNC_BODYdef cut(
itr: Iterable[T],
where: int | Callable... | from __future__ import annotations
from typing import Callable, Hashable, Iterable, Iterator, TypeVar
from functools import reduce
from itertools import chain, cycle, islice, tee
T = TypeVar("T")
def intersection(*items: Iterable[T]) -> set[T]:
"""Does an intersection over all collection of items
..code::... | |
9,605 | /home/hieuvd/dung_repo/raw/stars_01/automl_auto-sklearn/auto-sklearn | /home/hieuvd/dung_repo/raw/stars_01/automl_auto-sklearn/auto-sklearn/autosklearn/util/parallel.py | 5,6 | 1,33 | preload_modules | 7,33 | 6,33 | import multiprocessing
import sys
def preload_modules(context: multiprocessing.context.BaseContext) -> None:
FILL_FUNC_BODY | import multiprocessing
import sys
def preload_modules(context: multiprocessing.context.BaseContext) -> None:
"""Attempt to preload modules when using forkserver"""
FILL_FUNC_BODY | # NOTE: preloading and docstring
#
# This is just a best guess at why this is used, coming from this blogpost
# https://bnikolic.co.uk/blog/python/parallelism/2019/11/13/python-forkserver-preload.html
# Ideally we should identify subprocesses that get run with this and try limit the
# ne... | """Attempt to preload modules when using forkserver"""
# NOTE: preloading and docstring
#
# This is just a best guess at why this is used, coming from this blogpost
# https://bnikolic.co.uk/blog/python/parallelism/2019/11/13/python-forkserver-preload.html
# Ideally we should identify subpr... | 81 | 59 | 291 | 350 | import multiprocessing
import sys
def preload_modules(context: multiprocessing.context.BaseContext) -> None:
FILL_FUNC_BODY | import multiprocessing
import sys
def preload_modules(context: multiprocessing.context.BaseContext) -> None:
"""Attempt to preload modules when using forkserver"""
FILL_FUNC_BODY | |
9,606 | /home/hieuvd/dung_repo/raw/stars_01/automl_auto-sklearn/auto-sklearn | /home/hieuvd/dung_repo/raw/stars_01/automl_auto-sklearn/auto-sklearn/autosklearn/util/stopwatch.py | 113,120 | 71,240 | time_since | StopWatch | 149,172 | 120,172 | class StopWatch(Mapping[str, TimingTask]):
"""Class to collect timing tasks."""
def __init__(self) -> None:
self.tasks = {"_stopwatch_": TimingTask("_stopwatch_")}
self.tasks["_stopwatch_"].start()
def __contains__(self, name: object) -> bool:
return name in self.tasks
def __g... | class StopWatch(Mapping[str, TimingTask]):
"""Class to collect timing tasks."""
def __init__(self) -> None:
self.tasks = {"_stopwatch_": TimingTask("_stopwatch_")}
self.tasks["_stopwatch_"].start()
def __contains__(self, name: object) -> bool:
return name in self.tasks
def __g... | task = self.tasks.get(name, None)
if task is None:
if raises:
raise ValueError(f"Task not listed in {list(self.tasks.keys())}")
else:
return default
if phase == "start":
event_time = task.wall_start
elif phase == "end"... | """The wall clock time since a task either began or ended
Parameters
----------
name : str
The name of the task
phase : Literal["start", "end"] = "start"
From which phase you want to know the time elapsed since
default: float = 0.0
I... | 57 | 1,315 | 191 | 1,506 | from __future__ import annotations
from typing import Iterator, Mapping, Optional, Tuple
import sys
import time
from contextlib import contextmanager
from itertools import repeat
from typing_extensions import Literal
class TimingTask:
"""A task to start"""
def __init__(self, name: str):
"""
... | from __future__ import annotations
from typing import Iterator, Mapping, Optional, Tuple
import sys
import time
from contextlib import contextmanager
from itertools import repeat
from typing_extensions import Literal
class TimingTask:
"""A task to start"""
def __init__(self, name: str):
"""
... |
9,607 | /home/hieuvd/dung_repo/raw/stars_01/automl_auto-sklearn/auto-sklearn | /home/hieuvd/dung_repo/raw/stars_01/automl_auto-sklearn/auto-sklearn/autosklearn/util/stopwatch.py | 35,36 | 13,71 | stop | TimingTask | 37,41 | 36,41 | class TimingTask:
"""A task to start"""
def __init__(self, name: str):
"""
Parameters
----------
name : str
The name of the task
"""
self.name = name
self.cpu_start: Optional[float] = None
self.cpu_end: Optional[float] = None
s... | class TimingTask:
"""A task to start"""
def __init__(self, name: str):
"""
Parameters
----------
name : str
The name of the task
"""
self.name = name
self.cpu_start: Optional[float] = None
self.cpu_end: Optional[float] = None
s... | if not self.finished():
self.cpu_end = time.process_time()
self.wall_end = time.time()
| """Stop the task"""
if not self.finished():
self.cpu_end = time.process_time()
self.wall_end = time.time()
| 9 | 457 | 39 | 496 | from __future__ import annotations
from typing import Iterator, Mapping, Optional, Tuple
import sys
import time
from contextlib import contextmanager
from itertools import repeat
from typing_extensions import Literal
class TimingTask:
"""A task to start"""
def __init__(self, name: str):
"""
... | from __future__ import annotations
from typing import Iterator, Mapping, Optional, Tuple
import sys
import time
from contextlib import contextmanager
from itertools import repeat
from typing_extensions import Literal
class TimingTask:
"""A task to start"""
def __init__(self, name: str):
"""
... |
10,083 | /home/hieuvd/dung_repo/raw/stars_01/chenfei-wu_TaskMatrix/TaskMatrix | /home/hieuvd/dung_repo/raw/stars_01/chenfei-wu_TaskMatrix/TaskMatrix/LowCodeLLM/src/executingLLM.py | 34,35 | 26,43 | execute | executingLLM | 36,43 | 35,43 | class executingLLM:
def __init__(self, temperature) -> None:
self.prefix = EXECUTING_LLM_PREFIX
self.suffix = EXECUTING_LLM_SUFFIX
self.LLM = OpenAIWrapper(temperature)
self.messages = [{"role": "system", "content": "You are a helpful assistant."},
{"role": "... | class executingLLM:
def __init__(self, temperature) -> None:
self.prefix = EXECUTING_LLM_PREFIX
self.suffix = EXECUTING_LLM_SUFFIX
self.LLM = OpenAIWrapper(temperature)
self.messages = [{"role": "system", "content": "You are a helpful assistant."},
{"role": "... | messages = self.messages + history
messages.append({'role': 'user', "content": current_prompt + self.suffix})
response, status = self.LLM.run(messages)
if status:
return response
else:
return "OpenAI API error." | ''' provide LLM the dialogue history and the current prompt to get response '''
messages = self.messages + history
messages.append({'role': 'user', "content": current_prompt + self.suffix})
response, status = self.LLM.run(messages)
if status:
return response
e... | 24 | 148 | 77 | 225 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from openAIWrapper import OpenAIWrapper
EXECUTING_LLM_PREFIX = """Executing LLM is designed to provide outstanding responses.
Executing LLM will be given a overall task as the background of the conversation between the Executing LLM and human.
W... | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from openAIWrapper import OpenAIWrapper
EXECUTING_LLM_PREFIX = """Executing LLM is designed to provide outstanding responses.
Executing LLM will be given a overall task as the background of the conversation between the Executing LLM and human.
W... |
10,084 | /home/hieuvd/dung_repo/raw/stars_01/chenfei-wu_TaskMatrix/TaskMatrix | /home/hieuvd/dung_repo/raw/stars_01/chenfei-wu_TaskMatrix/TaskMatrix/LowCodeLLM/src/lowCodeLLM.py | 31,32 | 8,48 | _json2txt | lowCodeLLM | 33,48 | 32,48 | class lowCodeLLM:
def __init__(self, PLLM_temperature=0.4, ELLM_temperature=0):
self.PLLM = planningLLM(PLLM_temperature)
self.ELLM = executingLLM(ELLM_temperature)
def get_workflow(self, task_prompt):
return self.PLLM.get_workflow(task_prompt)
def extend_workflow(self, task_prompt... | class lowCodeLLM:
def __init__(self, PLLM_temperature=0.4, ELLM_temperature=0):
self.PLLM = planningLLM(PLLM_temperature)
self.ELLM = executingLLM(ELLM_temperature)
def get_workflow(self, task_prompt):
return self.PLLM.get_workflow(task_prompt)
def extend_workflow(self, task_prompt... | def json2text_step(step):
step_res = ""
step_res += step["stepId"] + ": [" + step["stepName"] + "]"
step_res += "[" + step["stepDescription"] + "]["
for jump in step["jumpLogic"]:
step_res += "[[" + jump["Condition"] + "][" + jump["Target"] + "]],"... | ''' convert the json workflow to text'''
def json2text_step(step):
step_res = ""
step_res += step["stepId"] + ": [" + step["stepName"] + "]"
step_res += "[" + step["stepDescription"] + "]["
for jump in step["jumpLogic"]:
step_res += "[[" + ... | 61 | 374 | 198 | 572 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from planningLLM import planningLLM
from executingLLM import executingLLM
import json
class lowCodeLLM:
def __init__(self, PLLM_temperature=0.4, ELLM_temperature=0):
self.PLLM = planningLLM(PLLM_temperature)
self.ELLM = execu... | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from planningLLM import planningLLM
from executingLLM import executingLLM
import json
class lowCodeLLM:
def __init__(self, PLLM_temperature=0.4, ELLM_temperature=0):
self.PLLM = planningLLM(PLLM_temperature)
self.ELLM = execu... |
10,232 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/app/app_settings.py | 19,20 | 6,55 | save_settings | AppSettings | 20,25 | 20,25 | class AppSettings():
def __init__(self, user_manager):
self.user_manager = user_manager
def get_settings(self, request):
file = self.user_manager.get_request_user_filepath(
request, "comfy.settings.json")
if os.path.isfile(file):
with open(file) as f:
... | class AppSettings():
def __init__(self, user_manager):
self.user_manager = user_manager
def get_settings(self, request):
file = self.user_manager.get_request_user_filepath(
request, "comfy.settings.json")
if os.path.isfile(file):
with open(file) as f:
... | file = self.user_manager.get_request_user_filepath(
request, "comfy.settings.json")
with open(file, "w") as f:
f.write(json.dumps(settings, indent=4))
| file = self.user_manager.get_request_user_filepath(
request, "comfy.settings.json")
with open(file, "w") as f:
f.write(json.dumps(settings, indent=4))
| 12 | 465 | 68 | 533 | import os
import json
from aiohttp import web
class AppSettings():
def __init__(self, user_manager):
self.user_manager = user_manager
def get_settings(self, request):
file = self.user_manager.get_request_user_filepath(
request, "comfy.settings.json")
if os.path.isfile(file... | import os
import json
from aiohttp import web
class AppSettings():
def __init__(self, user_manager):
self.user_manager = user_manager
def get_settings(self, request):
file = self.user_manager.get_request_user_filepath(
request, "comfy.settings.json")
if os.path.isfile(file... |
10,233 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/checkpoint_pickle.py | 9,10 | 8,14 | find_class | Unpickler | 10,14 | 10,14 | class Unpickler(pickle.Unpickler):
def find_class(self, module, name):
FILL_FUNC_BODY | class Unpickler(pickle.Unpickler):
def find_class(self, module, name):
FILL_FUNC_BODY | #TODO: safe unpickle
if module.startswith("pytorch_lightning"):
return Empty
return super().find_class(module, name)
| #TODO: safe unpickle
if module.startswith("pytorch_lightning"):
return Empty
return super().find_class(module, name)
| 10 | 39 | 50 | 89 | import pickle
load = pickle.load
class Empty:
pass
class Unpickler(pickle.Unpickler):
def find_class(self, module, name):
FILL_FUNC_BODY | import pickle
load = pickle.load
class Empty:
pass
class Unpickler(pickle.Unpickler):
def find_class(self, module, name):
FILL_FUNC_BODY |
10,234 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/clip_model.py | 15,16 | 4,23 | forward | CLIPAttention | 16,23 | 16,23 | class CLIPAttention(torch.nn.Module):
def __init__(self, embed_dim, heads, dtype, device, operations):
super().__init__()
self.heads = heads
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, dtype=dtype, device=device)
self.k_proj = operations.Linear(embed_dim, embed_... | class CLIPAttention(torch.nn.Module):
def __init__(self, embed_dim, heads, dtype, device, operations):
super().__init__()
self.heads = heads
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, dtype=dtype, device=device)
self.k_proj = operations.Linear(embed_dim, embed_... | q = self.q_proj(x)
k = self.k_proj(x)
v = self.v_proj(x)
out = optimized_attention(q, k, v, self.heads, mask)
return self.out_proj(out)
| q = self.q_proj(x)
k = self.k_proj(x)
v = self.v_proj(x)
out = optimized_attention(q, k, v, self.heads, mask)
return self.out_proj(out)
| 18 | 219 | 77 | 296 | import torch
from comfy.ldm.modules.attention import optimized_attention_for_device
class CLIPAttention(torch.nn.Module):
def __init__(self, embed_dim, heads, dtype, device, operations):
super().__init__()
self.heads = heads
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, ... | import torch
from comfy.ldm.modules.attention import optimized_attention_for_device
class CLIPAttention(torch.nn.Module):
def __init__(self, embed_dim, heads, dtype, device, operations):
super().__init__()
self.heads = heads
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, ... |
10,235 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/clip_model.py | 79,80 | 73,83 | forward | CLIPEmbeddings | 80,83 | 80,83 | class CLIPEmbeddings(torch.nn.Module):
def __init__(self, embed_dim, vocab_size=49408, num_positions=77, dtype=None, device=None):
super().__init__()
self.token_embedding = torch.nn.Embedding(vocab_size, embed_dim, dtype=dtype, device=device)
self.position_embedding = torch.nn.Embedding(num_... | class CLIPEmbeddings(torch.nn.Module):
def __init__(self, embed_dim, vocab_size=49408, num_positions=77, dtype=None, device=None):
super().__init__()
self.token_embedding = torch.nn.Embedding(vocab_size, embed_dim, dtype=dtype, device=device)
self.position_embedding = torch.nn.Embedding(num_... | return self.token_embedding(input_tokens) + self.position_embedding.weight
| return self.token_embedding(input_tokens) + self.position_embedding.weight
| 4 | 160 | 29 | 189 | import torch
from comfy.ldm.modules.attention import optimized_attention_for_device
class CLIPAttention(torch.nn.Module):
def __init__(self, embed_dim, heads, dtype, device, operations):
super().__init__()
self.heads = heads
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, ... | import torch
from comfy.ldm.modules.attention import optimized_attention_for_device
class CLIPAttention(torch.nn.Module):
def __init__(self, embed_dim, heads, dtype, device, operations):
super().__init__()
self.heads = heads
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, ... |
10,236 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/clip_model.py | 59,60 | 54,73 | forward | CLIPEncoder | 60,73 | 60,73 | class CLIPEncoder(torch.nn.Module):
def __init__(self, num_layers, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations):
super().__init__()
self.layers = torch.nn.ModuleList([CLIPLayer(embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, op... | class CLIPEncoder(torch.nn.Module):
def __init__(self, num_layers, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations):
super().__init__()
self.layers = torch.nn.ModuleList([CLIPLayer(embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, op... | optimized_attention = optimized_attention_for_device(x.device, mask=mask is not None, small_input=True)
if intermediate_output is not None:
if intermediate_output < 0:
intermediate_output = len(self.layers) + intermediate_output
intermediate = None
for i, l ... | optimized_attention = optimized_attention_for_device(x.device, mask=mask is not None, small_input=True)
if intermediate_output is not None:
if intermediate_output < 0:
intermediate_output = len(self.layers) + intermediate_output
intermediate = None
for i, l ... | 45 | 137 | 138 | 275 | import torch
from comfy.ldm.modules.attention import optimized_attention_for_device
class CLIPAttention(torch.nn.Module):
def __init__(self, embed_dim, heads, dtype, device, operations):
super().__init__()
self.heads = heads
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, ... | import torch
from comfy.ldm.modules.attention import optimized_attention_for_device
class CLIPAttention(torch.nn.Module):
def __init__(self, embed_dim, heads, dtype, device, operations):
super().__init__()
self.heads = heads
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, ... |
10,237 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/clip_model.py | 48,49 | 40,54 | forward | CLIPLayer | 49,54 | 49,54 | class CLIPLayer(torch.nn.Module):
def __init__(self, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations):
super().__init__()
self.layer_norm1 = operations.LayerNorm(embed_dim, dtype=dtype, device=device)
self.self_attn = CLIPAttention(embed_dim, heads, dt... | class CLIPLayer(torch.nn.Module):
def __init__(self, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations):
super().__init__()
self.layer_norm1 = operations.LayerNorm(embed_dim, dtype=dtype, device=device)
self.self_attn = CLIPAttention(embed_dim, heads, dt... | x += self.self_attn(self.layer_norm1(x), mask, optimized_attention)
x += self.mlp(self.layer_norm2(x))
return x
| x += self.self_attn(self.layer_norm1(x), mask, optimized_attention)
x += self.mlp(self.layer_norm2(x))
return x
| 10 | 196 | 55 | 251 | import torch
from comfy.ldm.modules.attention import optimized_attention_for_device
class CLIPAttention(torch.nn.Module):
def __init__(self, embed_dim, heads, dtype, device, operations):
super().__init__()
self.heads = heads
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, ... | import torch
from comfy.ldm.modules.attention import optimized_attention_for_device
class CLIPAttention(torch.nn.Module):
def __init__(self, embed_dim, heads, dtype, device, operations):
super().__init__()
self.heads = heads
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, ... |
10,238 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/clip_model.py | 34,35 | 27,40 | forward | CLIPMLP | 35,40 | 35,40 | class CLIPMLP(torch.nn.Module):
def __init__(self, embed_dim, intermediate_size, activation, dtype, device, operations):
super().__init__()
self.fc1 = operations.Linear(embed_dim, intermediate_size, bias=True, dtype=dtype, device=device)
self.activation = ACTIVATIONS[activation]
self... | class CLIPMLP(torch.nn.Module):
def __init__(self, embed_dim, intermediate_size, activation, dtype, device, operations):
super().__init__()
self.fc1 = operations.Linear(embed_dim, intermediate_size, bias=True, dtype=dtype, device=device)
self.activation = ACTIVATIONS[activation]
self... | x = self.fc1(x)
x = self.activation(x)
x = self.fc2(x)
return x
| x = self.fc1(x)
x = self.activation(x)
x = self.fc2(x)
return x
| 11 | 149 | 43 | 192 | import torch
from comfy.ldm.modules.attention import optimized_attention_for_device
class CLIPAttention(torch.nn.Module):
def __init__(self, embed_dim, heads, dtype, device, operations):
super().__init__()
self.heads = heads
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, ... | import torch
from comfy.ldm.modules.attention import optimized_attention_for_device
class CLIPAttention(torch.nn.Module):
def __init__(self, embed_dim, heads, dtype, device, operations):
super().__init__()
self.heads = heads
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, ... |
10,239 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/clip_model.py | 133,134 | 117,139 | forward | CLIPTextModel | 134,139 | 134,139 | class CLIPTextModel(torch.nn.Module):
def __init__(self, config_dict, dtype, device, operations):
super().__init__()
self.num_layers = config_dict["num_hidden_layers"]
self.text_model = CLIPTextModel_(config_dict, dtype, device, operations)
embed_dim = config_dict["hidden_size"]
... | class CLIPTextModel(torch.nn.Module):
def __init__(self, config_dict, dtype, device, operations):
super().__init__()
self.num_layers = config_dict["num_hidden_layers"]
self.text_model = CLIPTextModel_(config_dict, dtype, device, operations)
embed_dim = config_dict["hidden_size"]
... | x = self.text_model(*args, **kwargs)
out = self.text_projection(x[2])
return (x[0], x[1], out, x[2])
| x = self.text_model(*args, **kwargs)
out = self.text_projection(x[2])
return (x[0], x[1], out, x[2])
| 12 | 251 | 55 | 306 | import torch
from comfy.ldm.modules.attention import optimized_attention_for_device
class CLIPAttention(torch.nn.Module):
def __init__(self, embed_dim, heads, dtype, device, operations):
super().__init__()
self.heads = heads
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, ... | import torch
from comfy.ldm.modules.attention import optimized_attention_for_device
class CLIPAttention(torch.nn.Module):
def __init__(self, embed_dim, heads, dtype, device, operations):
super().__init__()
self.heads = heads
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, ... |
10,240 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/clip_model.py | 96,97 | 83,117 | forward | CLIPTextModel_ | 97,117 | 97,117 | class CLIPTextModel_(torch.nn.Module):
def __init__(self, config_dict, dtype, device, operations):
num_layers = config_dict["num_hidden_layers"]
embed_dim = config_dict["hidden_size"]
heads = config_dict["num_attention_heads"]
intermediate_size = config_dict["intermediate_size"]
... | class CLIPTextModel_(torch.nn.Module):
def __init__(self, config_dict, dtype, device, operations):
num_layers = config_dict["num_hidden_layers"]
embed_dim = config_dict["hidden_size"]
heads = config_dict["num_attention_heads"]
intermediate_size = config_dict["intermediate_size"]
... | x = self.embeddings(input_tokens)
mask = None
if attention_mask is not None:
mask = 1.0 - attention_mask.to(x.dtype).reshape((attention_mask.shape[0], 1, -1, attention_mask.shape[-1])).expand(attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1])
... | x = self.embeddings(input_tokens)
mask = None
if attention_mask is not None:
mask = 1.0 - attention_mask.to(x.dtype).reshape((attention_mask.shape[0], 1, -1, attention_mask.shape[-1])).expand(attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1])
... | 73 | 263 | 370 | 633 | import torch
from comfy.ldm.modules.attention import optimized_attention_for_device
class CLIPAttention(torch.nn.Module):
def __init__(self, embed_dim, heads, dtype, device, operations):
super().__init__()
self.heads = heads
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, ... | import torch
from comfy.ldm.modules.attention import optimized_attention_for_device
class CLIPAttention(torch.nn.Module):
def __init__(self, embed_dim, heads, dtype, device, operations):
super().__init__()
self.heads = heads
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, ... |
10,241 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/clip_model.py | 177,178 | 163,185 | forward | CLIPVision | 178,185 | 178,185 | class CLIPVision(torch.nn.Module):
def __init__(self, config_dict, dtype, device, operations):
super().__init__()
num_layers = config_dict["num_hidden_layers"]
embed_dim = config_dict["hidden_size"]
heads = config_dict["num_attention_heads"]
intermediate_size = config_dict["i... | class CLIPVision(torch.nn.Module):
def __init__(self, config_dict, dtype, device, operations):
super().__init__()
num_layers = config_dict["num_hidden_layers"]
embed_dim = config_dict["hidden_size"]
heads = config_dict["num_attention_heads"]
intermediate_size = config_dict["i... | x = self.embeddings(pixel_values)
x = self.pre_layrnorm(x)
#TODO: attention_mask?
x, i = self.encoder(x, mask=None, intermediate_output=intermediate_output)
pooled_output = self.post_layernorm(x[:, 0, :])
return x, i, pooled_output
| x = self.embeddings(pixel_values)
x = self.pre_layrnorm(x)
#TODO: attention_mask?
x, i = self.encoder(x, mask=None, intermediate_output=intermediate_output)
pooled_output = self.post_layernorm(x[:, 0, :])
return x, i, pooled_output
| 23 | 292 | 106 | 398 | import torch
from comfy.ldm.modules.attention import optimized_attention_for_device
class CLIPAttention(torch.nn.Module):
def __init__(self, embed_dim, heads, dtype, device, operations):
super().__init__()
self.heads = heads
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, ... | import torch
from comfy.ldm.modules.attention import optimized_attention_for_device
class CLIPAttention(torch.nn.Module):
def __init__(self, embed_dim, heads, dtype, device, operations):
super().__init__()
self.heads = heads
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, ... |
10,242 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/clip_model.py | 158,159 | 139,163 | forward | CLIPVisionEmbeddings | 159,163 | 159,163 | class CLIPVisionEmbeddings(torch.nn.Module):
def __init__(self, embed_dim, num_channels=3, patch_size=14, image_size=224, dtype=None, device=None, operations=None):
super().__init__()
self.class_embedding = torch.nn.Parameter(torch.empty(embed_dim, dtype=dtype, device=device))
self.patch_em... | class CLIPVisionEmbeddings(torch.nn.Module):
def __init__(self, embed_dim, num_channels=3, patch_size=14, image_size=224, dtype=None, device=None, operations=None):
super().__init__()
self.class_embedding = torch.nn.Parameter(torch.empty(embed_dim, dtype=dtype, device=device))
self.patch_em... | embeds = self.patch_embedding(pixel_values).flatten(2).transpose(1, 2)
return torch.cat([self.class_embedding.to(embeds.device).expand(pixel_values.shape[0], 1, -1), embeds], dim=1) + self.position_embedding.weight.to(embeds.device)
| embeds = self.patch_embedding(pixel_values).flatten(2).transpose(1, 2)
return torch.cat([self.class_embedding.to(embeds.device).expand(pixel_values.shape[0], 1, -1), embeds], dim=1) + self.position_embedding.weight.to(embeds.device)
| 12 | 279 | 99 | 378 | import torch
from comfy.ldm.modules.attention import optimized_attention_for_device
class CLIPAttention(torch.nn.Module):
def __init__(self, embed_dim, heads, dtype, device, operations):
super().__init__()
self.heads = heads
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, ... | import torch
from comfy.ldm.modules.attention import optimized_attention_for_device
class CLIPAttention(torch.nn.Module):
def __init__(self, embed_dim, heads, dtype, device, operations):
super().__init__()
self.heads = heads
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, ... |
10,243 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/clip_model.py | 191,192 | 185,195 | forward | CLIPVisionModelProjection | 192,195 | 192,195 | class CLIPVisionModelProjection(torch.nn.Module):
def __init__(self, config_dict, dtype, device, operations):
super().__init__()
self.vision_model = CLIPVision(config_dict, dtype, device, operations)
self.visual_projection = operations.Linear(config_dict["hidden_size"], config_dict["projecti... | class CLIPVisionModelProjection(torch.nn.Module):
def __init__(self, config_dict, dtype, device, operations):
super().__init__()
self.vision_model = CLIPVision(config_dict, dtype, device, operations)
self.visual_projection = operations.Linear(config_dict["hidden_size"], config_dict["projecti... | x = self.vision_model(*args, **kwargs)
out = self.visual_projection(x[2])
return (x[0], x[1], out)
| x = self.vision_model(*args, **kwargs)
out = self.visual_projection(x[2])
return (x[0], x[1], out)
| 11 | 127 | 48 | 175 | import torch
from comfy.ldm.modules.attention import optimized_attention_for_device
class CLIPAttention(torch.nn.Module):
def __init__(self, embed_dim, heads, dtype, device, operations):
super().__init__()
self.heads = heads
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, ... | import torch
from comfy.ldm.modules.attention import optimized_attention_for_device
class CLIPAttention(torch.nn.Module):
def __init__(self, embed_dim, heads, dtype, device, operations):
super().__init__()
self.heads = heads
self.q_proj = operations.Linear(embed_dim, embed_dim, bias=True, ... |
10,244 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/conds.py | 6,7 | 1,79 | lcm | 7,9 | 7,9 | import torch
import math
import comfy.utils
def lcm(a, b): #TODO: eventually replace by math.lcm (added in python3.9)
FILL_FUNC_BODYclass CONDRegular:
def __init__(self, cond):
self.cond = cond
def _copy_with(self, cond):
return self.__class__(cond)
def process_cond(self, batch_size, dev... | import torch
import math
import comfy.utils
def lcm(a, b): #TODO: eventually replace by math.lcm (added in python3.9)
FILL_FUNC_BODYclass CONDRegular:
def __init__(self, cond):
self.cond = cond
def _copy_with(self, cond):
return self.__class__(cond)
def process_cond(self, batch_size, dev... | return abs(a*b) // math.gcd(a, b)
| return abs(a*b) // math.gcd(a, b)
| 5 | 802 | 22 | 824 | import torch
import math
import comfy.utils
def lcm(a, b): #TODO: eventually replace by math.lcm (added in python3.9)
FILL_FUNC_BODYclass CONDRegular:
def __init__(self, cond):
self.cond = cond
def _copy_with(self, cond):
return self.__class__(cond)
def process_cond(self, batch_size, dev... | import torch
import math
import comfy.utils
def lcm(a, b): #TODO: eventually replace by math.lcm (added in python3.9)
FILL_FUNC_BODYclass CONDRegular:
def __init__(self, cond):
self.cond = cond
def _copy_with(self, cond):
return self.__class__(cond)
def process_cond(self, batch_size, dev... | |
10,245 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/conds.py | 72,73 | 65,79 | can_concat | CONDConstant | 73,77 | 73,77 | class CONDConstant(CONDRegular):
def __init__(self, cond):
self.cond = cond
def process_cond(self, batch_size, device, **kwargs):
return self._copy_with(self.cond)
def can_concat(self, other):
FILL_FUNC_BODY def concat(self, others):
return self.cond
| class CONDConstant(CONDRegular):
def __init__(self, cond):
self.cond = cond
def process_cond(self, batch_size, device, **kwargs):
return self._copy_with(self.cond)
def can_concat(self, other):
FILL_FUNC_BODY def concat(self, others):
return self.cond
| if self.cond != other.cond:
return False
return True
| if self.cond != other.cond:
return False
return True
| 8 | 98 | 25 | 123 | import torch
import math
import comfy.utils
def lcm(a, b): #TODO: eventually replace by math.lcm (added in python3.9)
return abs(a*b) // math.gcd(a, b)
class CONDRegular:
def __init__(self, cond):
self.cond = cond
def _copy_with(self, cond):
return self.__class__(cond)
def process_c... | import torch
import math
import comfy.utils
def lcm(a, b): #TODO: eventually replace by math.lcm (added in python3.9)
return abs(a*b) // math.gcd(a, b)
class CONDRegular:
def __init__(self, cond):
self.cond = cond
def _copy_with(self, cond):
return self.__class__(cond)
def process_c... |
10,246 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/conds.py | 37,38 | 36,65 | can_concat | CONDCrossAttn | 38,50 | 38,50 | class CONDCrossAttn(CONDRegular):
def can_concat(self, other):
FILL_FUNC_BODY def concat(self, others):
conds = [self.cond]
crossattn_max_len = self.cond.shape[1]
for x in others:
c = x.cond
crossattn_max_len = lcm(crossattn_max_len, c.shape[1])
conds.a... | class CONDCrossAttn(CONDRegular):
def can_concat(self, other):
FILL_FUNC_BODY def concat(self, others):
conds = [self.cond]
crossattn_max_len = self.cond.shape[1]
for x in others:
c = x.cond
crossattn_max_len = lcm(crossattn_max_len, c.shape[1])
conds.a... | s1 = self.cond.shape
s2 = other.cond.shape
if s1 != s2:
if s1[0] != s2[0] or s1[2] != s2[2]: #these 2 cases should not happen
return False
mult_min = lcm(s1[1], s2[1])
diff = mult_min // min(s1[1], s2[1])
if diff > 4: #arbitrary li... | s1 = self.cond.shape
s2 = other.cond.shape
if s1 != s2:
if s1[0] != s2[0] or s1[2] != s2[2]: #these 2 cases should not happen
return False
mult_min = lcm(s1[1], s2[1])
diff = mult_min // min(s1[1], s2[1])
if diff > 4: #arbitrary li... | 61 | 209 | 163 | 372 | import torch
import math
import comfy.utils
def lcm(a, b): #TODO: eventually replace by math.lcm (added in python3.9)
return abs(a*b) // math.gcd(a, b)
class CONDRegular:
def __init__(self, cond):
self.cond = cond
def _copy_with(self, cond):
return self.__class__(cond)
def process_c... | import torch
import math
import comfy.utils
def lcm(a, b): #TODO: eventually replace by math.lcm (added in python3.9)
return abs(a*b) // math.gcd(a, b)
class CONDRegular:
def __init__(self, cond):
self.cond = cond
def _copy_with(self, cond):
return self.__class__(cond)
def process_c... |
10,247 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/conds.py | 31,32 | 30,36 | process_cond | CONDNoiseShape | 32,36 | 32,36 | class CONDNoiseShape(CONDRegular):
def process_cond(self, batch_size, device, area, **kwargs):
FILL_FUNC_BODY | class CONDNoiseShape(CONDRegular):
def process_cond(self, batch_size, device, area, **kwargs):
FILL_FUNC_BODY | data = self.cond[:,:,area[2]:area[0] + area[2],area[3]:area[1] + area[3]]
return self._copy_with(comfy.utils.repeat_to_batch_size(data, batch_size).to(device))
| data = self.cond[:,:,area[2]:area[0] + area[2],area[3]:area[1] + area[3]]
return self._copy_with(comfy.utils.repeat_to_batch_size(data, batch_size).to(device))
| 10 | 43 | 75 | 118 | import torch
import math
import comfy.utils
def lcm(a, b): #TODO: eventually replace by math.lcm (added in python3.9)
return abs(a*b) // math.gcd(a, b)
class CONDRegular:
def __init__(self, cond):
self.cond = cond
def _copy_with(self, cond):
return self.__class__(cond)
def process_c... | import torch
import math
import comfy.utils
def lcm(a, b): #TODO: eventually replace by math.lcm (added in python3.9)
return abs(a*b) // math.gcd(a, b)
class CONDRegular:
def __init__(self, cond):
self.cond = cond
def _copy_with(self, cond):
return self.__class__(cond)
def process_c... |
10,248 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/conds.py | 24,25 | 9,30 | concat | CONDRegular | 25,30 | 25,30 | class CONDRegular:
def __init__(self, cond):
self.cond = cond
def _copy_with(self, cond):
return self.__class__(cond)
def process_cond(self, batch_size, device, **kwargs):
return self._copy_with(comfy.utils.repeat_to_batch_size(self.cond, batch_size).to(device))
def can_concat... | class CONDRegular:
def __init__(self, cond):
self.cond = cond
def _copy_with(self, cond):
return self.__class__(cond)
def process_cond(self, batch_size, device, **kwargs):
return self._copy_with(comfy.utils.repeat_to_batch_size(self.cond, batch_size).to(device))
def can_concat... | conds = [self.cond]
for x in others:
conds.append(x.cond)
return torch.cat(conds)
| conds = [self.cond]
for x in others:
conds.append(x.cond)
return torch.cat(conds)
| 10 | 156 | 45 | 201 | import torch
import math
import comfy.utils
def lcm(a, b): #TODO: eventually replace by math.lcm (added in python3.9)
return abs(a*b) // math.gcd(a, b)
class CONDRegular:
def __init__(self, cond):
self.cond = cond
def _copy_with(self, cond):
return self.__class__(cond)
def process_c... | import torch
import math
import comfy.utils
def lcm(a, b): #TODO: eventually replace by math.lcm (added in python3.9)
return abs(a*b) // math.gcd(a, b)
class CONDRegular:
def __init__(self, cond):
self.cond = cond
def _copy_with(self, cond):
return self.__class__(cond)
def process_c... |
10,250 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/diffusers_load.py | 12,13 | 1,37 | load_diffusers | 13,37 | 13,37 | import os
import comfy.sd
def first_file(path, filenames):
for f in filenames:
p = os.path.join(path, f)
if os.path.exists(p):
return p
return None
def load_diffusers(model_path, output_vae=True, output_clip=True, embedding_directory=None):
FILL_FUNC_BODY | import os
import comfy.sd
def first_file(path, filenames):
for f in filenames:
p = os.path.join(path, f)
if os.path.exists(p):
return p
return None
def load_diffusers(model_path, output_vae=True, output_clip=True, embedding_directory=None):
FILL_FUNC_BODY | diffusion_model_names = ["diffusion_pytorch_model.fp16.safetensors", "diffusion_pytorch_model.safetensors", "diffusion_pytorch_model.fp16.bin", "diffusion_pytorch_model.bin"]
unet_path = first_file(os.path.join(model_path, "unet"), diffusion_model_names)
vae_path = first_file(os.path.join(model_path, "vae")... | diffusion_model_names = ["diffusion_pytorch_model.fp16.safetensors", "diffusion_pytorch_model.safetensors", "diffusion_pytorch_model.fp16.bin", "diffusion_pytorch_model.bin"]
unet_path = first_file(os.path.join(model_path, "unet"), diffusion_model_names)
vae_path = first_file(os.path.join(model_path, "vae")... | 68 | 106 | 476 | 582 | import os
import comfy.sd
def first_file(path, filenames):
for f in filenames:
p = os.path.join(path, f)
if os.path.exists(p):
return p
return None
def load_diffusers(model_path, output_vae=True, output_clip=True, embedding_directory=None):
FILL_FUNC_BODY | import os
import comfy.sd
def first_file(path, filenames):
for f in filenames:
p = os.path.join(path, f)
if os.path.exists(p):
return p
return None
def load_diffusers(model_path, output_vae=True, output_clip=True, embedding_directory=None):
FILL_FUNC_BODY | |
10,251 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/latent_formats.py | 11,12 | 3,14 | process_out | LatentFormat | 12,14 | 12,14 | class LatentFormat:
scale_factor = 1.0
latent_rgb_factors = None
taesd_decoder_name = None
def process_in(self, latent):
return latent * self.scale_factor
def process_out(self, latent):
FILL_FUNC_BODY | class LatentFormat:
scale_factor = 1.0
latent_rgb_factors = None
taesd_decoder_name = None
def process_in(self, latent):
return latent * self.scale_factor
def process_out(self, latent):
FILL_FUNC_BODY | return latent / self.scale_factor
| return latent / self.scale_factor
| 4 | 82 | 13 | 95 | import torch
class LatentFormat:
scale_factor = 1.0
latent_rgb_factors = None
taesd_decoder_name = None
def process_in(self, latent):
return latent * self.scale_factor
def process_out(self, latent):
FILL_FUNC_BODYclass SD15(LatentFormat):
def __init__(self, scale_factor=0.18215):
... | import torch
class LatentFormat:
scale_factor = 1.0
latent_rgb_factors = None
taesd_decoder_name = None
def process_in(self, latent):
return latent * self.scale_factor
def process_out(self, latent):
FILL_FUNC_BODYclass SD15(LatentFormat):
def __init__(self, scale_factor=0.18215):
... |
10,252 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/latent_formats.py | 53,54 | 38,64 | process_in | SDXL_Playground_2_5 | 54,58 | 54,58 | class SDXL_Playground_2_5(LatentFormat):
def __init__(self):
self.scale_factor = 0.5
self.latents_mean = torch.tensor([-1.6574, 1.886, -1.383, 2.5155]).view(1, 4, 1, 1)
self.latents_std = torch.tensor([8.4927, 5.9022, 6.5498, 5.2299]).view(1, 4, 1, 1)
self.latent_rgb_factors = [
... | class SDXL_Playground_2_5(LatentFormat):
def __init__(self):
self.scale_factor = 0.5
self.latents_mean = torch.tensor([-1.6574, 1.886, -1.383, 2.5155]).view(1, 4, 1, 1)
self.latents_std = torch.tensor([8.4927, 5.9022, 6.5498, 5.2299]).view(1, 4, 1, 1)
self.latent_rgb_factors = [
... | latents_mean = self.latents_mean.to(latent.device, latent.dtype)
latents_std = self.latents_std.to(latent.device, latent.dtype)
return (latent - latents_mean) * self.scale_factor / latents_std
| latents_mean = self.latents_mean.to(latent.device, latent.dtype)
latents_std = self.latents_std.to(latent.device, latent.dtype)
return (latent - latents_mean) * self.scale_factor / latents_std
| 16 | 415 | 80 | 495 | import torch
class LatentFormat:
scale_factor = 1.0
latent_rgb_factors = None
taesd_decoder_name = None
def process_in(self, latent):
return latent * self.scale_factor
def process_out(self, latent):
return latent / self.scale_factor
class SD15(LatentFormat):
def __init__(self... | import torch
class LatentFormat:
scale_factor = 1.0
latent_rgb_factors = None
taesd_decoder_name = None
def process_in(self, latent):
return latent * self.scale_factor
def process_out(self, latent):
return latent / self.scale_factor
class SD15(LatentFormat):
def __init__(self... |
10,254 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ldm/cascade/common.py | 57,58 | 51,68 | forward | Attention2D | 58,68 | 58,68 | class Attention2D(nn.Module):
def __init__(self, c, nhead, dropout=0.0, dtype=None, device=None, operations=None):
super().__init__()
self.attn = OptimizedAttention(c, nhead, dtype=dtype, device=device, operations=operations)
# self.attn = nn.MultiheadAttention(c, nhead, dropout=dropout, bia... | class Attention2D(nn.Module):
def __init__(self, c, nhead, dropout=0.0, dtype=None, device=None, operations=None):
super().__init__()
self.attn = OptimizedAttention(c, nhead, dtype=dtype, device=device, operations=operations)
# self.attn = nn.MultiheadAttention(c, nhead, dropout=dropout, bia... | orig_shape = x.shape
x = x.view(x.size(0), x.size(1), -1).permute(0, 2, 1) # Bx4xHxW -> Bx(HxW)x4
if self_attn:
kv = torch.cat([x, kv], dim=1)
# x = self.attn(x, kv, kv, need_weights=False)[0]
x = self.attn(x, kv, kv)
x = x.permute(0, 2, 1).view(*orig_shape)
... | orig_shape = x.shape
x = x.view(x.size(0), x.size(1), -1).permute(0, 2, 1) # Bx4xHxW -> Bx(HxW)x4
if self_attn:
kv = torch.cat([x, kv], dim=1)
# x = self.attn(x, kv, kv, need_weights=False)[0]
x = self.attn(x, kv, kv)
x = x.permute(0, 2, 1).view(*orig_shape)
... | 40 | 161 | 175 | 336 | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
10,255 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ldm/cascade/common.py | 124,125 | 113,130 | forward | AttnBlock | 125,130 | 125,130 | class AttnBlock(nn.Module):
def __init__(self, c, c_cond, nhead, self_attn=True, dropout=0.0, dtype=None, device=None, operations=None):
super().__init__()
self.self_attn = self_attn
self.norm = LayerNorm2d_op(operations)(c, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
... | class AttnBlock(nn.Module):
def __init__(self, c, c_cond, nhead, self_attn=True, dropout=0.0, dtype=None, device=None, operations=None):
super().__init__()
self.self_attn = self_attn
self.norm = LayerNorm2d_op(operations)(c, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
... | kv = self.kv_mapper(kv)
x = x + self.attention(self.norm(x), kv, self_attn=self.self_attn)
return x
| kv = self.kv_mapper(kv)
x = x + self.attention(self.norm(x), kv, self_attn=self.self_attn)
return x
| 12 | 228 | 58 | 286 | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
10,256 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ldm/cascade/common.py | 28,29 | 27,31 | reset_parameters | Conv2d | 29,31 | 29,31 | class Conv2d(torch.nn.Conv2d):
def reset_parameters(self):
FILL_FUNC_BODY | class Conv2d(torch.nn.Conv2d):
def reset_parameters(self):
FILL_FUNC_BODY | return None
| return None
| 2 | 36 | 7 | 43 | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
10,257 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ldm/cascade/common.py | 142,143 | 130,147 | forward | FeedForwardBlock | 143,147 | 143,147 | class FeedForwardBlock(nn.Module):
def __init__(self, c, dropout=0.0, dtype=None, device=None, operations=None):
super().__init__()
self.norm = LayerNorm2d_op(operations)(c, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
self.channelwise = nn.Sequential(
operatio... | class FeedForwardBlock(nn.Module):
def __init__(self, c, dropout=0.0, dtype=None, device=None, operations=None):
super().__init__()
self.norm = LayerNorm2d_op(operations)(c, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
self.channelwise = nn.Sequential(
operatio... | x = x + self.channelwise(self.norm(x).permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
return x
| x = x + self.channelwise(self.norm(x).permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
return x
| 13 | 218 | 57 | 275 | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
10,258 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ldm/cascade/common.py | 84,85 | 77,90 | forward | GlobalResponseNorm | 85,90 | 85,90 | class GlobalResponseNorm(nn.Module):
"from https://github.com/facebookresearch/ConvNeXt-V2/blob/3608f67cc1dae164790c5d0aead7bf2d73d9719b/models/utils.py#L105"
def __init__(self, dim, dtype=None, device=None):
super().__init__()
self.gamma = nn.Parameter(torch.zeros(1, 1, 1, dim, dtype=dtype, dev... | class GlobalResponseNorm(nn.Module):
"from https://github.com/facebookresearch/ConvNeXt-V2/blob/3608f67cc1dae164790c5d0aead7bf2d73d9719b/models/utils.py#L105"
def __init__(self, dim, dtype=None, device=None):
super().__init__()
self.gamma = nn.Parameter(torch.zeros(1, 1, 1, dim, dtype=dtype, dev... | Gx = torch.norm(x, p=2, dim=(1, 2), keepdim=True)
Nx = Gx / (Gx.mean(dim=-1, keepdim=True) + 1e-6)
return self.gamma.to(device=x.device, dtype=x.dtype) * (x * Nx) + self.beta.to(device=x.device, dtype=x.dtype) + x
| Gx = torch.norm(x, p=2, dim=(1, 2), keepdim=True)
Nx = Gx / (Gx.mean(dim=-1, keepdim=True) + 1e-6)
return self.gamma.to(device=x.device, dtype=x.dtype) * (x * Nx) + self.beta.to(device=x.device, dtype=x.dtype) + x
| 27 | 203 | 119 | 322 | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
10,259 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ldm/cascade/common.py | 73,74 | 69,75 | forward | LayerNorm2d | 74,75 | 74,75 | class LayerNorm2d(operations.LayerNorm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def forward(self, x):
FILL_FUNC_BODY | class LayerNorm2d(operations.LayerNorm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def forward(self, x):
FILL_FUNC_BODY | return super().forward(x.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
| return super().forward(x.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
| 8 | 62 | 40 | 102 | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
10,260 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ldm/cascade/common.py | 24,25 | 23,27 | reset_parameters | Linear | 25,27 | 25,27 | class Linear(torch.nn.Linear):
def reset_parameters(self):
FILL_FUNC_BODY | class Linear(torch.nn.Linear):
def reset_parameters(self):
FILL_FUNC_BODY | return None
| return None
| 2 | 31 | 7 | 38 | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
10,261 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ldm/cascade/common.py | 42,43 | 31,51 | forward | OptimizedAttention | 43,51 | 43,51 | class OptimizedAttention(nn.Module):
def __init__(self, c, nhead, dropout=0.0, dtype=None, device=None, operations=None):
super().__init__()
self.heads = nhead
self.to_q = operations.Linear(c, c, bias=True, dtype=dtype, device=device)
self.to_k = operations.Linear(c, c, bias=True, d... | class OptimizedAttention(nn.Module):
def __init__(self, c, nhead, dropout=0.0, dtype=None, device=None, operations=None):
super().__init__()
self.heads = nhead
self.to_q = operations.Linear(c, c, bias=True, dtype=dtype, device=device)
self.to_k = operations.Linear(c, c, bias=True, d... | q = self.to_q(q)
k = self.to_k(k)
v = self.to_v(v)
out = optimized_attention(q, k, v, self.heads)
return self.out_proj(out)
| q = self.to_q(q)
k = self.to_k(k)
v = self.to_v(v)
out = optimized_attention(q, k, v, self.heads)
return self.out_proj(out)
| 17 | 207 | 77 | 284 | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
10,262 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ldm/cascade/common.py | 104,105 | 90,113 | forward | ResBlock | 105,113 | 105,113 | class ResBlock(nn.Module):
def __init__(self, c, c_skip=0, kernel_size=3, dropout=0.0, dtype=None, device=None, operations=None): # , num_heads=4, expansion=2):
super().__init__()
self.depthwise = operations.Conv2d(c, c, kernel_size=kernel_size, padding=kernel_size // 2, groups=c, dtype=dtype, devi... | class ResBlock(nn.Module):
def __init__(self, c, c_skip=0, kernel_size=3, dropout=0.0, dtype=None, device=None, operations=None): # , num_heads=4, expansion=2):
super().__init__()
self.depthwise = operations.Conv2d(c, c, kernel_size=kernel_size, padding=kernel_size // 2, groups=c, dtype=dtype, devi... | x_res = x
x = self.norm(self.depthwise(x))
if x_skip is not None:
x = torch.cat([x, x_skip], dim=1)
x = self.channelwise(x.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
return x + x_res
| x_res = x
x = self.norm(self.depthwise(x))
if x_skip is not None:
x = torch.cat([x, x_skip], dim=1)
x = self.channelwise(x.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
return x + x_res
| 29 | 323 | 110 | 433 | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
10,263 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ldm/cascade/common.py | 155,156 | 147,162 | forward | TimestepBlock | 156,162 | 156,162 | class TimestepBlock(nn.Module):
def __init__(self, c, c_timestep, conds=['sca'], dtype=None, device=None, operations=None):
super().__init__()
self.mapper = operations.Linear(c_timestep, c * 2, dtype=dtype, device=device)
self.conds = conds
for cname in conds:
setattr(sel... | class TimestepBlock(nn.Module):
def __init__(self, c, c_timestep, conds=['sca'], dtype=None, device=None, operations=None):
super().__init__()
self.mapper = operations.Linear(c_timestep, c * 2, dtype=dtype, device=device)
self.conds = conds
for cname in conds:
setattr(sel... | t = t.chunk(len(self.conds) + 1, dim=1)
a, b = self.mapper(t[0])[:, :, None, None].chunk(2, dim=1)
for i, c in enumerate(self.conds):
ac, bc = getattr(self, f"mapper_{c}")(t[i + 1])[:, :, None, None].chunk(2, dim=1)
a, b = a + ac, b + bc
return x * (1 + a) + b
| t = t.chunk(len(self.conds) + 1, dim=1)
a, b = self.mapper(t[0])[:, :, None, None].chunk(2, dim=1)
for i, c in enumerate(self.conds):
ac, bc = getattr(self, f"mapper_{c}")(t[i + 1])[:, :, None, None].chunk(2, dim=1)
a, b = a + ac, b + bc
return x * (1 + a) + b
| 47 | 168 | 146 | 314 | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
10,264 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ldm/cascade/stage_c_coder.py | 35,36 | 24,43 | forward | EfficientNetEncoder | 36,43 | 36,43 | class EfficientNetEncoder(nn.Module):
def __init__(self, c_latent=16):
super().__init__()
self.backbone = torchvision.models.efficientnet_v2_s().features.eval()
self.mapper = nn.Sequential(
nn.Conv2d(1280, c_latent, kernel_size=1, bias=False),
nn.BatchNorm2d(c_latent,... | class EfficientNetEncoder(nn.Module):
def __init__(self, c_latent=16):
super().__init__()
self.backbone = torchvision.models.efficientnet_v2_s().features.eval()
self.mapper = nn.Sequential(
nn.Conv2d(1280, c_latent, kernel_size=1, bias=False),
nn.BatchNorm2d(c_latent,... | x = x * 0.5 + 0.5
x = (x - self.mean.view([3,1,1])) / self.std.view([3,1,1])
o = self.mapper(self.backbone(x))
return o
# Fast Decoder for Stage C latents. E.g. 16 x 24 x 24 -> 3 x 192 x 192
| x = x * 0.5 + 0.5
x = (x - self.mean.view([3,1,1])) / self.std.view([3,1,1])
o = self.mapper(self.backbone(x))
return o
# Fast Decoder for Stage C latents. E.g. 16 x 24 x 24 -> 3 x 192 x 192
| 38 | 235 | 114 | 349 | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
10,265 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ldm/cascade/stage_c_coder.py | 82,83 | 43,85 | forward | Previewer | 83,85 | 83,85 | class Previewer(nn.Module):
def __init__(self, c_in=16, c_hidden=512, c_out=3):
super().__init__()
self.blocks = nn.Sequential(
nn.Conv2d(c_in, c_hidden, kernel_size=1), # 16 channels to 512 channels
nn.GELU(),
nn.BatchNorm2d(c_hidden),
nn.Conv2d(c_h... | class Previewer(nn.Module):
def __init__(self, c_in=16, c_hidden=512, c_out=3):
super().__init__()
self.blocks = nn.Sequential(
nn.Conv2d(c_in, c_hidden, kernel_size=1), # 16 channels to 512 channels
nn.GELU(),
nn.BatchNorm2d(c_hidden),
nn.Conv2d(c_h... | return (self.blocks(x) - 0.5) * 2.0
| return (self.blocks(x) - 0.5) * 2.0
| 6 | 622 | 24 | 646 | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
10,266 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ldm/cascade/stage_c_coder.py | 94,95 | 85,96 | decode | StageC_coder | 95,96 | 95,96 | class StageC_coder(nn.Module):
def __init__(self):
super().__init__()
self.previewer = Previewer()
self.encoder = EfficientNetEncoder()
def encode(self, x):
return self.encoder(x)
def decode(self, x):
FILL_FUNC_BODY | class StageC_coder(nn.Module):
def __init__(self):
super().__init__()
self.previewer = Previewer()
self.encoder = EfficientNetEncoder()
def encode(self, x):
return self.encoder(x)
def decode(self, x):
FILL_FUNC_BODY | return self.previewer(x)
| return self.previewer(x)
| 2 | 94 | 12 | 106 | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
10,267 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ldm/modules/diffusionmodules/upscaling.py | 17,19 | 10,60 | register_schedule | AbstractLowScaleModel | 19,44 | 19,44 | class AbstractLowScaleModel(nn.Module):
# for concatenating a downsampled image to the latent representation
def __init__(self, noise_schedule_config=None):
super(AbstractLowScaleModel, self).__init__()
if noise_schedule_config is not None:
self.register_schedule(**noise_schedule_con... | class AbstractLowScaleModel(nn.Module):
# for concatenating a downsampled image to the latent representation
def __init__(self, noise_schedule_config=None):
super(AbstractLowScaleModel, self).__init__()
if noise_schedule_config is not None:
self.register_schedule(**noise_schedule_con... | betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end,
cosine_s=cosine_s)
alphas = 1. - betas
alphas_cumprod = np.cumprod(alphas, axis=0)
alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
t... | betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end,
cosine_s=cosine_s)
alphas = 1. - betas
alphas_cumprod = np.cumprod(alphas, axis=0)
alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
t... | 83 | 385 | 549 | 934 | import torch
import torch.nn as nn
import numpy as np
from functools import partial
from .util import extract_into_tensor, make_beta_schedule
from comfy.ldm.util import default
class AbstractLowScaleModel(nn.Module):
# for concatenating a downsampled image to the latent representation
def __init__(self, nois... | import torch
import torch.nn as nn
import numpy as np
from functools import partial
from .util import extract_into_tensor, make_beta_schedule
from comfy.ldm.util import default
class AbstractLowScaleModel(nn.Module):
# for concatenating a downsampled image to the latent representation
def __init__(self, nois... |
10,268 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ldm/modules/diffusionmodules/upscaling.py | 76,77 | 71,86 | forward | ImageConcatWithNoiseAugmentation | 77,86 | 77,86 | class ImageConcatWithNoiseAugmentation(AbstractLowScaleModel):
def __init__(self, noise_schedule_config, max_noise_level=1000, to_cuda=False):
super().__init__(noise_schedule_config=noise_schedule_config)
self.max_noise_level = max_noise_level
def forward(self, x, noise_level=None, seed=None):
... | class ImageConcatWithNoiseAugmentation(AbstractLowScaleModel):
def __init__(self, noise_schedule_config, max_noise_level=1000, to_cuda=False):
super().__init__(noise_schedule_config=noise_schedule_config)
self.max_noise_level = max_noise_level
def forward(self, x, noise_level=None, seed=None):
... | if noise_level is None:
noise_level = torch.randint(0, self.max_noise_level, (x.shape[0],), device=x.device).long()
else:
assert isinstance(noise_level, torch.Tensor)
z = self.q_sample(x, noise_level, seed=seed)
return z, noise_level
| if noise_level is None:
noise_level = torch.randint(0, self.max_noise_level, (x.shape[0],), device=x.device).long()
else:
assert isinstance(noise_level, torch.Tensor)
z = self.q_sample(x, noise_level, seed=seed)
return z, noise_level
| 22 | 116 | 107 | 223 | import torch
import torch.nn as nn
import numpy as np
from functools import partial
from .util import extract_into_tensor, make_beta_schedule
from comfy.ldm.util import default
class AbstractLowScaleModel(nn.Module):
# for concatenating a downsampled image to the latent representation
def __init__(self, nois... | import torch
import torch.nn as nn
import numpy as np
from functools import partial
from .util import extract_into_tensor, make_beta_schedule
from comfy.ldm.util import default
class AbstractLowScaleModel(nn.Module):
# for concatenating a downsampled image to the latent representation
def __init__(self, nois... |
10,269 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ldm/modules/diffusionmodules/upscaling.py | 66,67 | 60,71 | forward | SimpleImageConcat | 67,71 | 67,71 | class SimpleImageConcat(AbstractLowScaleModel):
# no noise level conditioning
def __init__(self):
super(SimpleImageConcat, self).__init__(noise_schedule_config=None)
self.max_noise_level = 0
def forward(self, x):
FILL_FUNC_BODY | class SimpleImageConcat(AbstractLowScaleModel):
# no noise level conditioning
def __init__(self):
super(SimpleImageConcat, self).__init__(noise_schedule_config=None)
self.max_noise_level = 0
def forward(self, x):
FILL_FUNC_BODY | # fix to constant noise level
return x, torch.zeros(x.shape[0], device=x.device).long()
| # fix to constant noise level
return x, torch.zeros(x.shape[0], device=x.device).long()
| 10 | 81 | 39 | 120 | import torch
import torch.nn as nn
import numpy as np
from functools import partial
from .util import extract_into_tensor, make_beta_schedule
from comfy.ldm.util import default
class AbstractLowScaleModel(nn.Module):
# for concatenating a downsampled image to the latent representation
def __init__(self, nois... | import torch
import torch.nn as nn
import numpy as np
from functools import partial
from .util import extract_into_tensor, make_beta_schedule
from comfy.ldm.util import default
class AbstractLowScaleModel(nn.Module):
# for concatenating a downsampled image to the latent representation
def __init__(self, nois... |
10,270 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ldm/modules/distributions/distributions.py | 65,66 | 1,93 | normal_kl | 72,93 | 66,93 | import torch
import numpy as np
class AbstractDistribution:
def sample(self):
raise NotImplementedError()
def mode(self):
raise NotImplementedError()
class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
retur... | import torch
import numpy as np
class AbstractDistribution:
def sample(self):
raise NotImplementedError()
def mode(self):
raise NotImplementedError()
class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
retur... | tensor = None
for obj in (mean1, logvar1, mean2, logvar2):
if isinstance(obj, torch.Tensor):
tensor = obj
break
assert tensor is not None, "at least one argument must be a Tensor"
# Force variances to be Tensors. Broadcasting helps convert scalars to
# Tensors, but i... | """
source: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/losses.py#L12
Compute the KL divergence between two gaussians.
Shapes are automatically broadcasted, so batches can be compared to
scalars, among other use cases.
"""
tensor ... | 88 | 789 | 252 | 1,041 | import torch
import numpy as np
class AbstractDistribution:
def sample(self):
raise NotImplementedError()
def mode(self):
raise NotImplementedError()
class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
retur... | import torch
import numpy as np
class AbstractDistribution:
def sample(self):
raise NotImplementedError()
def mode(self):
raise NotImplementedError()
class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
retur... | |
10,271 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ldm/modules/distributions/distributions.py | 6,7 | 5,13 | sample | AbstractDistribution | 7,9 | 7,9 | class AbstractDistribution:
def sample(self):
FILL_FUNC_BODY def mode(self):
raise NotImplementedError()
| class AbstractDistribution:
def sample(self):
FILL_FUNC_BODY def mode(self):
raise NotImplementedError()
| raise NotImplementedError()
| raise NotImplementedError()
| 2 | 41 | 12 | 53 | import torch
import numpy as np
class AbstractDistribution:
def sample(self):
FILL_FUNC_BODY def mode(self):
raise NotImplementedError()
class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
return self.value
def m... | import torch
import numpy as np
class AbstractDistribution:
def sample(self):
FILL_FUNC_BODY def mode(self):
raise NotImplementedError()
class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
return self.value
def m... |
10,272 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ldm/modules/distributions/distributions.py | 53,54 | 24,65 | nll | DiagonalGaussianDistribution | 54,61 | 54,61 | class DiagonalGaussianDistribution(object):
def __init__(self, parameters, deterministic=False):
self.parameters = parameters
self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)
self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
self.deterministic = deterministic
self... | class DiagonalGaussianDistribution(object):
def __init__(self, parameters, deterministic=False):
self.parameters = parameters
self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)
self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
self.deterministic = deterministic
self... | if self.deterministic:
return torch.Tensor([0.])
logtwopi = np.log(2.0 * np.pi)
return 0.5 * torch.sum(
logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
dim=dims)
| if self.deterministic:
return torch.Tensor([0.])
logtwopi = np.log(2.0 * np.pi)
return 0.5 * torch.sum(
logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
dim=dims)
| 24 | 447 | 99 | 546 | import torch
import numpy as np
class AbstractDistribution:
def sample(self):
raise NotImplementedError()
def mode(self):
raise NotImplementedError()
class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
retur... | import torch
import numpy as np
class AbstractDistribution:
def sample(self):
raise NotImplementedError()
def mode(self):
raise NotImplementedError()
class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
retur... |
10,273 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ldm/modules/distributions/distributions.py | 17,18 | 13,24 | sample | DiracDistribution | 18,20 | 18,20 | class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
FILL_FUNC_BODY def mode(self):
return self.value
| class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
FILL_FUNC_BODY def mode(self):
return self.value
| return self.value
| return self.value
| 2 | 61 | 9 | 70 | import torch
import numpy as np
class AbstractDistribution:
def sample(self):
raise NotImplementedError()
def mode(self):
raise NotImplementedError()
class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
FILL_FUNC_BOD... | import torch
import numpy as np
class AbstractDistribution:
def sample(self):
raise NotImplementedError()
def mode(self):
raise NotImplementedError()
class DiracDistribution(AbstractDistribution):
def __init__(self, value):
self.value = value
def sample(self):
FILL_FUNC_BOD... |
10,276 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ldm/util.py | 118,120 | 90,198 | step | AdamWwithEMAandWings | 125,198 | 120,198 | class AdamWwithEMAandWings(optim.Optimizer):
# credit to https://gist.github.com/crowsonkb/65f7265353f403714fce3b2595e0b298
def __init__(self, params, lr=1.e-3, betas=(0.9, 0.999), eps=1.e-8, # TODO: check hyperparameters before using
weight_decay=1.e-2, amsgrad=False, ema_decay=0.9999, # em... | class AdamWwithEMAandWings(optim.Optimizer):
# credit to https://gist.github.com/crowsonkb/65f7265353f403714fce3b2595e0b298
def __init__(self, params, lr=1.e-3, betas=(0.9, 0.999), eps=1.e-8, # TODO: check hyperparameters before using
weight_decay=1.e-2, amsgrad=False, ema_decay=0.9999, # em... | loss = None
if closure is not None:
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
params_with_grad = []
grads = []
exp_avgs = []
exp_avg_sqs = []
ema_params_with_grad = []
... | """Performs a single optimization step.
Args:
closure (callable, optional): A closure that reevaluates the model
and returns the loss.
"""
loss = None
if closure is not None:
with torch.enable_grad():
loss = closure()
... | 197 | 612 | 883 | 1,495 | import importlib
import torch
from torch import optim
import numpy as np
from inspect import isfunction
from PIL import Image, ImageDraw, ImageFont
def log_txt_as_img(wh, xc, size=10):
# wh a tuple of (width, height)
# xc a list of captions to plot
b = len(xc)
txts = list()
for bi in range(b):
... | import importlib
import torch
from torch import optim
import numpy as np
from inspect import isfunction
from PIL import Image, ImageDraw, ImageFont
def log_txt_as_img(wh, xc, size=10):
# wh a tuple of (width, height)
# xc a list of captions to plot
b = len(xc)
txts = list()
for bi in range(b):
... |
10,278 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ops.py | 22,23 | 1,164 | cast_bias_weight | 23,34 | 23,34 | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | bias = None
non_blocking = comfy.model_management.device_supports_non_blocking(input.device)
if s.bias is not None:
bias = s.bias.to(device=input.device, dtype=input.dtype, non_blocking=non_blocking)
if s.bias_function is not None:
bias = s.bias_function(bias)
weight = s.weig... | bias = None
non_blocking = comfy.model_management.device_supports_non_blocking(input.device)
if s.bias is not None:
bias = s.bias.to(device=input.device, dtype=input.dtype, non_blocking=non_blocking)
if s.bias_function is not None:
bias = s.bias_function(bias)
weight = s.weig... | 40 | 1,622 | 182 | 1,804 | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | |
10,279 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ops.py | 62,63 | 54,68 | forward | Conv2d | 63,68 | 63,68 | class Conv2d(torch.nn.Conv2d, CastWeightBiasOp):
def reset_parameters(self):
return None
def forward_comfy_cast_weights(self, input):
weight, bias = cast_bias_weight(self, input)
return self._conv_forward(input, weight, bias)
def forward(self, *args, **k... | class Conv2d(torch.nn.Conv2d, CastWeightBiasOp):
def reset_parameters(self):
return None
def forward_comfy_cast_weights(self, input):
weight, bias = cast_bias_weight(self, input)
return self._conv_forward(input, weight, bias)
def forward(self, *args, **k... | if self.comfy_cast_weights:
return self.forward_comfy_cast_weights(*args, **kwargs)
else:
return super().forward(*args, **kwargs)
| if self.comfy_cast_weights:
return self.forward_comfy_cast_weights(*args, **kwargs)
else:
return super().forward(*args, **kwargs)
| 9 | 111 | 55 | 166 | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
10,280 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ops.py | 76,77 | 68,82 | forward | Conv3d | 77,82 | 77,82 | class Conv3d(torch.nn.Conv3d, CastWeightBiasOp):
def reset_parameters(self):
return None
def forward_comfy_cast_weights(self, input):
weight, bias = cast_bias_weight(self, input)
return self._conv_forward(input, weight, bias)
def forward(self, *args, **k... | class Conv3d(torch.nn.Conv3d, CastWeightBiasOp):
def reset_parameters(self):
return None
def forward_comfy_cast_weights(self, input):
weight, bias = cast_bias_weight(self, input)
return self._conv_forward(input, weight, bias)
def forward(self, *args, **k... | if self.comfy_cast_weights:
return self.forward_comfy_cast_weights(*args, **kwargs)
else:
return super().forward(*args, **kwargs)
| if self.comfy_cast_weights:
return self.forward_comfy_cast_weights(*args, **kwargs)
else:
return super().forward(*args, **kwargs)
| 9 | 111 | 55 | 166 | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
10,281 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ops.py | 119,120 | 115,136 | forward_comfy_cast_weights | ConvTranspose2d | 120,130 | 120,130 | class ConvTranspose2d(torch.nn.ConvTranspose2d, CastWeightBiasOp):
def reset_parameters(self):
return None
def forward_comfy_cast_weights(self, input, output_size=None):
FILL_FUNC_BODY def forward(self, *args, **kwargs):
if self.comfy_cast_weights:
ret... | class ConvTranspose2d(torch.nn.ConvTranspose2d, CastWeightBiasOp):
def reset_parameters(self):
return None
def forward_comfy_cast_weights(self, input, output_size=None):
FILL_FUNC_BODY def forward(self, *args, **kwargs):
if self.comfy_cast_weights:
ret... | num_spatial_dims = 2
output_padding = self._output_padding(
input, output_size, self.stride, self.padding, self.kernel_size,
num_spatial_dims, self.dilation)
weight, bias = cast_bias_weight(self, input)
return torch.nn.functional.conv_tran... | num_spatial_dims = 2
output_padding = self._output_padding(
input, output_size, self.stride, self.padding, self.kernel_size,
num_spatial_dims, self.dilation)
weight, bias = cast_bias_weight(self, input)
return torch.nn.functional.conv_tran... | 28 | 138 | 140 | 278 | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
10,282 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ops.py | 86,87 | 82,97 | forward_comfy_cast_weights | GroupNorm | 87,90 | 87,90 | class GroupNorm(torch.nn.GroupNorm, CastWeightBiasOp):
def reset_parameters(self):
return None
def forward_comfy_cast_weights(self, input):
FILL_FUNC_BODY def forward(self, *args, **kwargs):
if self.comfy_cast_weights:
return self.forward_comfy_cast_we... | class GroupNorm(torch.nn.GroupNorm, CastWeightBiasOp):
def reset_parameters(self):
return None
def forward_comfy_cast_weights(self, input):
FILL_FUNC_BODY def forward(self, *args, **kwargs):
if self.comfy_cast_weights:
return self.forward_comfy_cast_we... | weight, bias = cast_bias_weight(self, input)
return torch.nn.functional.group_norm(input, self.num_groups, weight, bias, self.eps)
| weight, bias = cast_bias_weight(self, input)
return torch.nn.functional.group_norm(input, self.num_groups, weight, bias, self.eps)
| 11 | 125 | 52 | 177 | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
10,283 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ops.py | 101,102 | 97,115 | forward_comfy_cast_weights | LayerNorm | 102,109 | 102,109 | class LayerNorm(torch.nn.LayerNorm, CastWeightBiasOp):
def reset_parameters(self):
return None
def forward_comfy_cast_weights(self, input):
FILL_FUNC_BODY def forward(self, *args, **kwargs):
if self.comfy_cast_weights:
return self.forward_comfy_cast_we... | class LayerNorm(torch.nn.LayerNorm, CastWeightBiasOp):
def reset_parameters(self):
return None
def forward_comfy_cast_weights(self, input):
FILL_FUNC_BODY def forward(self, *args, **kwargs):
if self.comfy_cast_weights:
return self.forward_comfy_cast_we... | if self.weight is not None:
weight, bias = cast_bias_weight(self, input)
else:
weight = None
bias = None
return torch.nn.functional.layer_norm(input, self.normalized_shape, weight, bias, self.eps)
| if self.weight is not None:
weight, bias = cast_bias_weight(self, input)
else:
weight = None
bias = None
return torch.nn.functional.layer_norm(input, self.normalized_shape, weight, bias, self.eps)
| 23 | 125 | 81 | 206 | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
10,284 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ops.py | 48,49 | 40,54 | forward | Linear | 49,54 | 49,54 | class Linear(torch.nn.Linear, CastWeightBiasOp):
def reset_parameters(self):
return None
def forward_comfy_cast_weights(self, input):
weight, bias = cast_bias_weight(self, input)
return torch.nn.functional.linear(input, weight, bias)
def forward(self, *a... | class Linear(torch.nn.Linear, CastWeightBiasOp):
def reset_parameters(self):
return None
def forward_comfy_cast_weights(self, input):
weight, bias = cast_bias_weight(self, input)
return torch.nn.functional.linear(input, weight, bias)
def forward(self, *a... | if self.comfy_cast_weights:
return self.forward_comfy_cast_weights(*args, **kwargs)
else:
return super().forward(*args, **kwargs)
| if self.comfy_cast_weights:
return self.forward_comfy_cast_weights(*args, **kwargs)
else:
return super().forward(*args, **kwargs)
| 9 | 110 | 55 | 165 | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
10,285 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/ops.py | 130,131 | 39,146 | forward | disable_weight_init | 131,136 | 131,136 | class disable_weight_init:
class Linear(torch.nn.Linear, CastWeightBiasOp):
def reset_parameters(self):
return None
def forward_comfy_cast_weights(self, input):
weight, bias = cast_bias_weight(self, input)
return torch.nn.functional.linear(input, weight, bias)
... | class disable_weight_init:
class Linear(torch.nn.Linear, CastWeightBiasOp):
def reset_parameters(self):
return None
def forward_comfy_cast_weights(self, input):
weight, bias = cast_bias_weight(self, input)
return torch.nn.functional.linear(input, weight, bias)
... | if self.comfy_cast_weights:
return self.forward_comfy_cast_weights(*args, **kwargs)
else:
return super().forward(*args, **kwargs)
| if self.comfy_cast_weights:
return self.forward_comfy_cast_weights(*args, **kwargs)
else:
return super().forward(*args, **kwargs)
| 9 | 1,123 | 55 | 1,178 | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... | """
This file is part of ComfyUI.
Copyright (C) 2024 Stability AI
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
10,286 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/options.py | 4,5 | 1,7 | enable_args_parsing | 5,7 | 5,7 |
args_parsing = False
def enable_args_parsing(enable=True):
FILL_FUNC_BODY |
args_parsing = False
def enable_args_parsing(enable=True):
FILL_FUNC_BODY | global args_parsing
args_parsing = enable
| global args_parsing
args_parsing = enable
| 5 | 32 | 17 | 49 |
args_parsing = False
def enable_args_parsing(enable=True):
FILL_FUNC_BODY |
args_parsing = False
def enable_args_parsing(enable=True):
FILL_FUNC_BODY | |
10,287 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/sample.py | 8,9 | 1,45 | prepare_noise | 13,27 | 9,27 | import torch
import comfy.model_management
import comfy.samplers
import comfy.utils
import numpy as np
import logging
def prepare_noise(latent_image, seed, noise_inds=None):
FILL_FUNC_BODYdef prepare_sampling(model, noise_shape, positive, negative, noise_mask):
logging.warning("Warning: comfy.sample.prepare_sampli... | import torch
import comfy.model_management
import comfy.samplers
import comfy.utils
import numpy as np
import logging
def prepare_noise(latent_image, seed, noise_inds=None):
"""
creates random noise given a latent image and a seed.
optional arg skip can be used to skip and discard x number of noise generat... | generator = torch.manual_seed(seed)
if noise_inds is None:
return torch.randn(latent_image.size(), dtype=latent_image.dtype, layout=latent_image.layout, generator=generator, device="cpu")
unique_inds, inverse = np.unique(noise_inds, return_inverse=True)
noises = []
for i in range(unique... | """
creates random noise given a latent image and a seed.
optional arg skip can be used to skip and discard x number of noise generations for a given seed
"""
generator = torch.manual_seed(seed)
if noise_inds is None:
return torch.randn(latent_image.size(), dtype=latent_image.dtype, layo... | 52 | 642 | 246 | 888 | import torch
import comfy.model_management
import comfy.samplers
import comfy.utils
import numpy as np
import logging
def prepare_noise(latent_image, seed, noise_inds=None):
FILL_FUNC_BODYdef prepare_sampling(model, noise_shape, positive, negative, noise_mask):
logging.warning("Warning: comfy.sample.prepare_sampli... | import torch
import comfy.model_management
import comfy.samplers
import comfy.utils
import numpy as np
import logging
def prepare_noise(latent_image, seed, noise_inds=None):
"""
creates random noise given a latent image and a seed.
optional arg skip can be used to skip and discard x number of noise generat... | |
10,288 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/sampler_helpers.py | 32,33 | 1,77 | get_additional_models | 34,53 | 33,53 | import torch
import comfy.model_management
import comfy.conds
def prepare_mask(noise_mask, shape, device):
"""ensures noise mask is of proper dimensions"""
noise_mask = torch.nn.functional.interpolate(noise_mask.reshape((-1, 1, noise_mask.shape[-2], noise_mask.shape[-1])), size=(shape[2], shape[3]), mode="bili... | import torch
import comfy.model_management
import comfy.conds
def prepare_mask(noise_mask, shape, device):
"""ensures noise mask is of proper dimensions"""
noise_mask = torch.nn.functional.interpolate(noise_mask.reshape((-1, 1, noise_mask.shape[-2], noise_mask.shape[-1])), size=(shape[2], shape[3]), mode="bili... | cnets = []
gligen = []
for k in conds:
cnets += get_models_from_cond(conds[k], "control")
gligen += get_models_from_cond(conds[k], "gligen")
control_nets = set(cnets)
inference_memory = 0
control_models = []
for m in control_nets:
control_models += m.get_models()
... | """loads additional models in conditioning"""
cnets = []
gligen = []
for k in conds:
cnets += get_models_from_cond(conds[k], "control")
gligen += get_models_from_cond(conds[k], "gligen")
control_nets = set(cnets)
inference_memory = 0
control_models = []
for m in contro... | 52 | 673 | 190 | 863 | import torch
import comfy.model_management
import comfy.conds
def prepare_mask(noise_mask, shape, device):
"""ensures noise mask is of proper dimensions"""
noise_mask = torch.nn.functional.interpolate(noise_mask.reshape((-1, 1, noise_mask.shape[-2], noise_mask.shape[-1])), size=(shape[2], shape[3]), mode="bili... | import torch
import comfy.model_management
import comfy.conds
def prepare_mask(noise_mask, shape, device):
"""ensures noise mask is of proper dimensions"""
noise_mask = torch.nn.functional.interpolate(noise_mask.reshape((-1, 1, noise_mask.shape[-2], noise_mask.shape[-1])), size=(shape[2], shape[3]), mode="bili... | |
10,289 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/sdxl_clip.py | 15,16 | 5,18 | load_sd | SDXLClipG | 16,18 | 16,18 | class SDXLClipG(sd1_clip.SDClipModel):
def __init__(self, device="cpu", max_length=77, freeze=True, layer="penultimate", layer_idx=None, dtype=None):
if layer == "penultimate":
layer="hidden"
layer_idx=-2
textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(... | class SDXLClipG(sd1_clip.SDClipModel):
def __init__(self, device="cpu", max_length=77, freeze=True, layer="penultimate", layer_idx=None, dtype=None):
if layer == "penultimate":
layer="hidden"
layer_idx=-2
textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(... | return super().load_sd(sd)
| return super().load_sd(sd)
| 2 | 242 | 14 | 256 | from comfy import sd1_clip
import torch
import os
class SDXLClipG(sd1_clip.SDClipModel):
def __init__(self, device="cpu", max_length=77, freeze=True, layer="penultimate", layer_idx=None, dtype=None):
if layer == "penultimate":
layer="hidden"
layer_idx=-2
textmodel_json_conf... | from comfy import sd1_clip
import torch
import os
class SDXLClipG(sd1_clip.SDClipModel):
def __init__(self, device="cpu", max_length=77, freeze=True, layer="penultimate", layer_idx=None, dtype=None):
if layer == "penultimate":
layer="hidden"
layer_idx=-2
textmodel_json_conf... |
10,290 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/sdxl_clip.py | 58,59 | 37,64 | load_sd | SDXLClipModel | 59,64 | 59,64 | class SDXLClipModel(torch.nn.Module):
def __init__(self, device="cpu", dtype=None):
super().__init__()
self.clip_l = sd1_clip.SDClipModel(layer="hidden", layer_idx=-2, device=device, dtype=dtype, layer_norm_hidden_state=False)
self.clip_g = SDXLClipG(device=device, dtype=dtype)
def set_... | class SDXLClipModel(torch.nn.Module):
def __init__(self, device="cpu", dtype=None):
super().__init__()
self.clip_l = sd1_clip.SDClipModel(layer="hidden", layer_idx=-2, device=device, dtype=dtype, layer_norm_hidden_state=False)
self.clip_g = SDXLClipG(device=device, dtype=dtype)
def set_... | if "text_model.encoder.layers.30.mlp.fc1.weight" in sd:
return self.clip_g.load_sd(sd)
else:
return self.clip_l.load_sd(sd)
| if "text_model.encoder.layers.30.mlp.fc1.weight" in sd:
return self.clip_g.load_sd(sd)
else:
return self.clip_l.load_sd(sd)
| 9 | 378 | 68 | 446 | from comfy import sd1_clip
import torch
import os
class SDXLClipG(sd1_clip.SDClipModel):
def __init__(self, device="cpu", max_length=77, freeze=True, layer="penultimate", layer_idx=None, dtype=None):
if layer == "penultimate":
layer="hidden"
layer_idx=-2
textmodel_json_conf... | from comfy import sd1_clip
import torch
import os
class SDXLClipG(sd1_clip.SDClipModel):
def __init__(self, device="cpu", max_length=77, freeze=True, layer="penultimate", layer_idx=None, dtype=None):
if layer == "penultimate":
layer="hidden"
layer_idx=-2
textmodel_json_conf... |
10,291 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/sdxl_clip.py | 28,29 | 23,37 | tokenize_with_weights | SDXLTokenizer | 29,34 | 29,34 | class SDXLTokenizer:
def __init__(self, embedding_directory=None):
self.clip_l = sd1_clip.SDTokenizer(embedding_directory=embedding_directory)
self.clip_g = SDXLClipGTokenizer(embedding_directory=embedding_directory)
def tokenize_with_weights(self, text:str, return_word_ids=False):
FILL_FUNC_BO... | class SDXLTokenizer:
def __init__(self, embedding_directory=None):
self.clip_l = sd1_clip.SDTokenizer(embedding_directory=embedding_directory)
self.clip_g = SDXLClipGTokenizer(embedding_directory=embedding_directory)
def tokenize_with_weights(self, text:str, return_word_ids=False):
FILL_FUNC_BO... | out = {}
out["g"] = self.clip_g.tokenize_with_weights(text, return_word_ids)
out["l"] = self.clip_l.tokenize_with_weights(text, return_word_ids)
return out
| out = {}
out["g"] = self.clip_g.tokenize_with_weights(text, return_word_ids)
out["l"] = self.clip_l.tokenize_with_weights(text, return_word_ids)
return out
| 13 | 148 | 73 | 221 | from comfy import sd1_clip
import torch
import os
class SDXLClipG(sd1_clip.SDClipModel):
def __init__(self, device="cpu", max_length=77, freeze=True, layer="penultimate", layer_idx=None, dtype=None):
if layer == "penultimate":
layer="hidden"
layer_idx=-2
textmodel_json_conf... | from comfy import sd1_clip
import torch
import os
class SDXLClipG(sd1_clip.SDClipModel):
def __init__(self, device="cpu", max_length=77, freeze=True, layer="penultimate", layer_idx=None, dtype=None):
if layer == "penultimate":
layer="hidden"
layer_idx=-2
textmodel_json_conf... |
10,292 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/sdxl_clip.py | 83,84 | 77,86 | load_sd | StableCascadeClipG | 84,86 | 84,86 | class StableCascadeClipG(sd1_clip.SDClipModel):
def __init__(self, device="cpu", max_length=77, freeze=True, layer="hidden", layer_idx=-1, dtype=None):
textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_config_bigg.json")
super().__init__(device=device, freeze=fr... | class StableCascadeClipG(sd1_clip.SDClipModel):
def __init__(self, device="cpu", max_length=77, freeze=True, layer="hidden", layer_idx=-1, dtype=None):
textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_config_bigg.json")
super().__init__(device=device, freeze=fr... | return super().load_sd(sd)
| return super().load_sd(sd)
| 2 | 230 | 14 | 244 | from comfy import sd1_clip
import torch
import os
class SDXLClipG(sd1_clip.SDClipModel):
def __init__(self, device="cpu", max_length=77, freeze=True, layer="penultimate", layer_idx=None, dtype=None):
if layer == "penultimate":
layer="hidden"
layer_idx=-2
textmodel_json_conf... | from comfy import sd1_clip
import torch
import os
class SDXLClipG(sd1_clip.SDClipModel):
def __init__(self, device="cpu", max_length=77, freeze=True, layer="penultimate", layer_idx=None, dtype=None):
if layer == "penultimate":
layer="hidden"
layer_idx=-2
textmodel_json_conf... |
10,294 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/t2i_adapter/adapter.py | 134,135 | 103,159 | forward | Adapter | 135,159 | 135,159 | class Adapter(nn.Module):
def __init__(self, channels=[320, 640, 1280, 1280], nums_rb=3, cin=64, ksize=3, sk=False, use_conv=True, xl=True):
super(Adapter, self).__init__()
self.unshuffle_amount = 8
resblock_no_downsample = []
resblock_downsample = [3, 2, 1]
self.xl = xl
... | class Adapter(nn.Module):
def __init__(self, channels=[320, 640, 1280, 1280], nums_rb=3, cin=64, ksize=3, sk=False, use_conv=True, xl=True):
super(Adapter, self).__init__()
self.unshuffle_amount = 8
resblock_no_downsample = []
resblock_downsample = [3, 2, 1]
self.xl = xl
... | # unshuffle
x = self.unshuffle(x)
# extract features
features = []
x = self.conv_in(x)
for i in range(len(self.channels)):
for j in range(self.nums_rb):
idx = i * self.nums_rb + j
x = self.body[idx](x)
if self.xl:
... | # unshuffle
x = self.unshuffle(x)
# extract features
features = []
x = self.conv_in(x)
for i in range(len(self.channels)):
for j in range(self.nums_rb):
idx = i * self.nums_rb + j
x = self.body[idx](x)
if self.xl:
... | 52 | 534 | 208 | 742 | #taken from https://github.com/TencentARC/T2I-Adapter
import torch
import torch.nn as nn
from collections import OrderedDict
def conv_nd(dims, *args, **kwargs):
"""
Create a 1D, 2D, or 3D convolution module.
"""
if dims == 1:
return nn.Conv1d(*args, **kwargs)
elif dims == 2:
return... | #taken from https://github.com/TencentARC/T2I-Adapter
import torch
import torch.nn as nn
from collections import OrderedDict
def conv_nd(dims, *args, **kwargs):
"""
Create a 1D, 2D, or 3D convolution module.
"""
if dims == 1:
return nn.Conv1d(*args, **kwargs)
elif dims == 2:
return... |
10,295 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/t2i_adapter/adapter.py | 282,283 | 264,294 | forward | Adapter_light | 283,294 | 283,294 | class Adapter_light(nn.Module):
def __init__(self, channels=[320, 640, 1280, 1280], nums_rb=3, cin=64):
super(Adapter_light, self).__init__()
self.unshuffle_amount = 8
self.unshuffle = nn.PixelUnshuffle(self.unshuffle_amount)
self.input_channels = cin // (self.unshuffle_amount * self... | class Adapter_light(nn.Module):
def __init__(self, channels=[320, 640, 1280, 1280], nums_rb=3, cin=64):
super(Adapter_light, self).__init__()
self.unshuffle_amount = 8
self.unshuffle = nn.PixelUnshuffle(self.unshuffle_amount)
self.input_channels = cin // (self.unshuffle_amount * self... | # unshuffle
x = self.unshuffle(x)
# extract features
features = []
for i in range(len(self.channels)):
x = self.body[i](x)
features.append(None)
features.append(None)
features.append(x)
return features
| # unshuffle
x = self.unshuffle(x)
# extract features
features = []
for i in range(len(self.channels)):
x = self.body[i](x)
features.append(None)
features.append(None)
features.append(x)
return features
| 23 | 339 | 95 | 434 | #taken from https://github.com/TencentARC/T2I-Adapter
import torch
import torch.nn as nn
from collections import OrderedDict
def conv_nd(dims, *args, **kwargs):
"""
Create a 1D, 2D, or 3D convolution module.
"""
if dims == 1:
return nn.Conv1d(*args, **kwargs)
elif dims == 2:
return... | #taken from https://github.com/TencentARC/T2I-Adapter
import torch
import torch.nn as nn
from collections import OrderedDict
def conv_nd(dims, *args, **kwargs):
"""
Create a 1D, 2D, or 3D convolution module.
"""
if dims == 1:
return nn.Conv1d(*args, **kwargs)
elif dims == 2:
return... |
10,296 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/t2i_adapter/adapter.py | 57,58 | 33,67 | forward | Downsample | 58,67 | 58,67 | class Downsample(nn.Module):
"""
A downsampling layer with an optional convolution.
:param channels: channels in the inputs and outputs.
:param use_conv: a bool determining if a convolution is applied.
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
downsampling ... | class Downsample(nn.Module):
"""
A downsampling layer with an optional convolution.
:param channels: channels in the inputs and outputs.
:param use_conv: a bool determining if a convolution is applied.
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
downsampling ... | assert x.shape[1] == self.channels
if not self.use_conv:
padding = [x.shape[2] % 2, x.shape[3] % 2]
self.op.padding = padding
x = self.op(x)
return x
| assert x.shape[1] == self.channels
if not self.use_conv:
padding = [x.shape[2] % 2, x.shape[3] % 2]
self.op.padding = padding
x = self.op(x)
return x
| 23 | 321 | 84 | 405 | #taken from https://github.com/TencentARC/T2I-Adapter
import torch
import torch.nn as nn
from collections import OrderedDict
def conv_nd(dims, *args, **kwargs):
"""
Create a 1D, 2D, or 3D convolution module.
"""
if dims == 1:
return nn.Conv1d(*args, **kwargs)
elif dims == 2:
return... | #taken from https://github.com/TencentARC/T2I-Adapter
import torch
import torch.nn as nn
from collections import OrderedDict
def conv_nd(dims, *args, **kwargs):
"""
Create a 1D, 2D, or 3D convolution module.
"""
if dims == 1:
return nn.Conv1d(*args, **kwargs)
elif dims == 2:
return... |
10,297 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/t2i_adapter/adapter.py | 162,163 | 159,168 | forward | LayerNorm | 163,168 | 163,168 | class LayerNorm(nn.LayerNorm):
"""Subclass torch's LayerNorm to handle fp16."""
def forward(self, x: torch.Tensor):
FILL_FUNC_BODY | class LayerNorm(nn.LayerNorm):
"""Subclass torch's LayerNorm to handle fp16."""
def forward(self, x: torch.Tensor):
FILL_FUNC_BODY | orig_type = x.dtype
ret = super().forward(x.type(torch.float32))
return ret.type(orig_type)
| orig_type = x.dtype
ret = super().forward(x.type(torch.float32))
return ret.type(orig_type)
| 8 | 56 | 47 | 103 | #taken from https://github.com/TencentARC/T2I-Adapter
import torch
import torch.nn as nn
from collections import OrderedDict
def conv_nd(dims, *args, **kwargs):
"""
Create a 1D, 2D, or 3D convolution module.
"""
if dims == 1:
return nn.Conv1d(*args, **kwargs)
elif dims == 2:
return... | #taken from https://github.com/TencentARC/T2I-Adapter
import torch
import torch.nn as nn
from collections import OrderedDict
def conv_nd(dims, *args, **kwargs):
"""
Create a 1D, 2D, or 3D convolution module.
"""
if dims == 1:
return nn.Conv1d(*args, **kwargs)
elif dims == 2:
return... |
10,298 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/t2i_adapter/adapter.py | 170,171 | 168,174 | forward | QuickGELU | 171,174 | 171,174 | class QuickGELU(nn.Module):
def forward(self, x: torch.Tensor):
FILL_FUNC_BODY | class QuickGELU(nn.Module):
def forward(self, x: torch.Tensor):
FILL_FUNC_BODY | return x * torch.sigmoid(1.702 * x)
| return x * torch.sigmoid(1.702 * x)
| 6 | 37 | 25 | 62 | #taken from https://github.com/TencentARC/T2I-Adapter
import torch
import torch.nn as nn
from collections import OrderedDict
def conv_nd(dims, *args, **kwargs):
"""
Create a 1D, 2D, or 3D convolution module.
"""
if dims == 1:
return nn.Conv1d(*args, **kwargs)
elif dims == 2:
return... | #taken from https://github.com/TencentARC/T2I-Adapter
import torch
import torch.nn as nn
from collections import OrderedDict
def conv_nd(dims, *args, **kwargs):
"""
Create a 1D, 2D, or 3D convolution module.
"""
if dims == 1:
return nn.Conv1d(*args, **kwargs)
elif dims == 2:
return... |
10,299 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/t2i_adapter/adapter.py | 187,188 | 174,197 | attention | ResidualAttentionBlock | 188,191 | 188,191 | class ResidualAttentionBlock(nn.Module):
def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
super().__init__()
self.attn = nn.MultiheadAttention(d_model, n_head)
self.ln_1 = LayerNorm(d_model)
self.mlp = nn.Sequential(
OrderedDict([("c_fc", n... | class ResidualAttentionBlock(nn.Module):
def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
super().__init__()
self.attn = nn.MultiheadAttention(d_model, n_head)
self.ln_1 = LayerNorm(d_model)
self.mlp = nn.Sequential(
OrderedDict([("c_fc", n... | self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
| self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
| 17 | 283 | 83 | 366 | #taken from https://github.com/TencentARC/T2I-Adapter
import torch
import torch.nn as nn
from collections import OrderedDict
def conv_nd(dims, *args, **kwargs):
"""
Create a 1D, 2D, or 3D convolution module.
"""
if dims == 1:
return nn.Conv1d(*args, **kwargs)
elif dims == 2:
return... | #taken from https://github.com/TencentARC/T2I-Adapter
import torch
import torch.nn as nn
from collections import OrderedDict
def conv_nd(dims, *args, **kwargs):
"""
Create a 1D, 2D, or 3D convolution module.
"""
if dims == 1:
return nn.Conv1d(*args, **kwargs)
elif dims == 2:
return... |
10,300 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/t2i_adapter/adapter.py | 88,89 | 67,103 | forward | ResnetBlock | 89,103 | 89,103 | class ResnetBlock(nn.Module):
def __init__(self, in_c, out_c, down, ksize=3, sk=False, use_conv=True):
super().__init__()
ps = ksize // 2
if in_c != out_c or sk == False:
self.in_conv = nn.Conv2d(in_c, out_c, ksize, 1, ps)
else:
# print('n_in')
sel... | class ResnetBlock(nn.Module):
def __init__(self, in_c, out_c, down, ksize=3, sk=False, use_conv=True):
super().__init__()
ps = ksize // 2
if in_c != out_c or sk == False:
self.in_conv = nn.Conv2d(in_c, out_c, ksize, 1, ps)
else:
# print('n_in')
sel... | if self.down == True:
x = self.down_opt(x)
if self.in_conv is not None: # edit
x = self.in_conv(x)
h = self.block1(x)
h = self.act(h)
h = self.block2(h)
if self.skep is not None:
return h + self.skep(x)
else:
retur... | if self.down == True:
x = self.down_opt(x)
if self.in_conv is not None: # edit
x = self.in_conv(x)
h = self.block1(x)
h = self.act(h)
h = self.block2(h)
if self.skep is not None:
return h + self.skep(x)
else:
retur... | 40 | 318 | 132 | 450 | #taken from https://github.com/TencentARC/T2I-Adapter
import torch
import torch.nn as nn
from collections import OrderedDict
def conv_nd(dims, *args, **kwargs):
"""
Create a 1D, 2D, or 3D convolution module.
"""
if dims == 1:
return nn.Conv1d(*args, **kwargs)
elif dims == 2:
return... | #taken from https://github.com/TencentARC/T2I-Adapter
import torch
import torch.nn as nn
from collections import OrderedDict
def conv_nd(dims, *args, **kwargs):
"""
Create a 1D, 2D, or 3D convolution module.
"""
if dims == 1:
return nn.Conv1d(*args, **kwargs)
elif dims == 2:
return... |
10,301 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/t2i_adapter/adapter.py | 233,234 | 226,241 | forward | ResnetBlock_light | 234,241 | 234,241 | class ResnetBlock_light(nn.Module):
def __init__(self, in_c):
super().__init__()
self.block1 = nn.Conv2d(in_c, in_c, 3, 1, 1)
self.act = nn.ReLU()
self.block2 = nn.Conv2d(in_c, in_c, 3, 1, 1)
def forward(self, x):
FILL_FUNC_BODY | class ResnetBlock_light(nn.Module):
def __init__(self, in_c):
super().__init__()
self.block1 = nn.Conv2d(in_c, in_c, 3, 1, 1)
self.act = nn.ReLU()
self.block2 = nn.Conv2d(in_c, in_c, 3, 1, 1)
def forward(self, x):
FILL_FUNC_BODY | h = self.block1(x)
h = self.act(h)
h = self.block2(h)
return h + x
| h = self.block1(x)
h = self.act(h)
h = self.block2(h)
return h + x
| 13 | 129 | 48 | 177 | #taken from https://github.com/TencentARC/T2I-Adapter
import torch
import torch.nn as nn
from collections import OrderedDict
def conv_nd(dims, *args, **kwargs):
"""
Create a 1D, 2D, or 3D convolution module.
"""
if dims == 1:
return nn.Conv1d(*args, **kwargs)
elif dims == 2:
return... | #taken from https://github.com/TencentARC/T2I-Adapter
import torch
import torch.nn as nn
from collections import OrderedDict
def conv_nd(dims, *args, **kwargs):
"""
Create a 1D, 2D, or 3D convolution module.
"""
if dims == 1:
return nn.Conv1d(*args, **kwargs)
elif dims == 2:
return... |
10,302 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/t2i_adapter/adapter.py | 210,211 | 197,226 | forward | StyleAdapter | 211,226 | 211,226 | class StyleAdapter(nn.Module):
def __init__(self, width=1024, context_dim=768, num_head=8, n_layes=3, num_token=4):
super().__init__()
scale = width ** -0.5
self.transformer_layes = nn.Sequential(*[ResidualAttentionBlock(width, num_head) for _ in range(n_layes)])
self.num_token = n... | class StyleAdapter(nn.Module):
def __init__(self, width=1024, context_dim=768, num_head=8, n_layes=3, num_token=4):
super().__init__()
scale = width ** -0.5
self.transformer_layes = nn.Sequential(*[ResidualAttentionBlock(width, num_head) for _ in range(n_layes)])
self.num_token = n... | # x shape [N, HW+1, C]
style_embedding = self.style_embedding + torch.zeros(
(x.shape[0], self.num_token, self.style_embedding.shape[-1]), device=x.device)
x = torch.cat([x, style_embedding], dim=1)
x = self.ln_pre(x)
x = x.permute(1, 0, 2) # NLD -> LND
x = s... | # x shape [N, HW+1, C]
style_embedding = self.style_embedding + torch.zeros(
(x.shape[0], self.num_token, self.style_embedding.shape[-1]), device=x.device)
x = torch.cat([x, style_embedding], dim=1)
x = self.ln_pre(x)
x = x.permute(1, 0, 2) # NLD -> LND
x = s... | 56 | 227 | 221 | 448 | #taken from https://github.com/TencentARC/T2I-Adapter
import torch
import torch.nn as nn
from collections import OrderedDict
def conv_nd(dims, *args, **kwargs):
"""
Create a 1D, 2D, or 3D convolution module.
"""
if dims == 1:
return nn.Conv1d(*args, **kwargs)
elif dims == 2:
return... | #taken from https://github.com/TencentARC/T2I-Adapter
import torch
import torch.nn as nn
from collections import OrderedDict
def conv_nd(dims, *args, **kwargs):
"""
Create a 1D, 2D, or 3D convolution module.
"""
if dims == 1:
return nn.Conv1d(*args, **kwargs)
elif dims == 2:
return... |
10,303 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/t2i_adapter/adapter.py | 254,255 | 241,264 | forward | extractor | 255,264 | 255,264 | class extractor(nn.Module):
def __init__(self, in_c, inter_c, out_c, nums_rb, down=False):
super().__init__()
self.in_conv = nn.Conv2d(in_c, inter_c, 1, 1, 0)
self.body = []
for _ in range(nums_rb):
self.body.append(ResnetBlock_light(inter_c))
self.body = nn.Seque... | class extractor(nn.Module):
def __init__(self, in_c, inter_c, out_c, nums_rb, down=False):
super().__init__()
self.in_conv = nn.Conv2d(in_c, inter_c, 1, 1, 0)
self.body = []
for _ in range(nums_rb):
self.body.append(ResnetBlock_light(inter_c))
self.body = nn.Seque... | if self.down == True:
x = self.down_opt(x)
x = self.in_conv(x)
x = self.body(x)
x = self.out_conv(x)
return x
| if self.down == True:
x = self.down_opt(x)
x = self.in_conv(x)
x = self.body(x)
x = self.out_conv(x)
return x
| 18 | 223 | 71 | 294 | #taken from https://github.com/TencentARC/T2I-Adapter
import torch
import torch.nn as nn
from collections import OrderedDict
def conv_nd(dims, *args, **kwargs):
"""
Create a 1D, 2D, or 3D convolution module.
"""
if dims == 1:
return nn.Conv1d(*args, **kwargs)
elif dims == 2:
return... | #taken from https://github.com/TencentARC/T2I-Adapter
import torch
import torch.nn as nn
from collections import OrderedDict
def conv_nd(dims, *args, **kwargs):
"""
Create a 1D, 2D, or 3D convolution module.
"""
if dims == 1:
return nn.Conv1d(*args, **kwargs)
elif dims == 2:
return... |
10,304 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/taesd/taesd.py | 37,38 | 1,78 | Decoder | 38,46 | 38,46 | #!/usr/bin/env python3
"""
Tiny AutoEncoder for Stable Diffusion
(DNN for encoding / decoding SD's latent space)
"""
import torch
import torch.nn as nn
import comfy.utils
import comfy.ops
def conv(n_in, n_out, **kwargs):
return comfy.ops.disable_weight_init.Conv2d(n_in, n_out, 3, padding=1, **kwargs)
class Clamp... | #!/usr/bin/env python3
"""
Tiny AutoEncoder for Stable Diffusion
(DNN for encoding / decoding SD's latent space)
"""
import torch
import torch.nn as nn
import comfy.utils
import comfy.ops
def conv(n_in, n_out, **kwargs):
return comfy.ops.disable_weight_init.Conv2d(n_in, n_out, 3, padding=1, **kwargs)
class Clamp... | return nn.Sequential(
Clamp(), conv(4, 64), nn.ReLU(),
Block(64, 64), Block(64, 64), Block(64, 64), nn.Upsample(scale_factor=2), conv(64, 64, bias=False),
Block(64, 64), Block(64, 64), Block(64, 64), nn.Upsample(scale_factor=2), conv(64, 64, bias=False),
Block(64, 64), Block(64, 64),... | return nn.Sequential(
Clamp(), conv(4, 64), nn.ReLU(),
Block(64, 64), Block(64, 64), Block(64, 64), nn.Upsample(scale_factor=2), conv(64, 64, bias=False),
Block(64, 64), Block(64, 64), Block(64, 64), nn.Upsample(scale_factor=2), conv(64, 64, bias=False),
Block(64, 64), Block(64, 64),... | 41 | 1,017 | 226 | 1,243 | #!/usr/bin/env python3
"""
Tiny AutoEncoder for Stable Diffusion
(DNN for encoding / decoding SD's latent space)
"""
import torch
import torch.nn as nn
import comfy.utils
import comfy.ops
def conv(n_in, n_out, **kwargs):
return comfy.ops.disable_weight_init.Conv2d(n_in, n_out, 3, padding=1, **kwargs)
class Clamp... | #!/usr/bin/env python3
"""
Tiny AutoEncoder for Stable Diffusion
(DNN for encoding / decoding SD's latent space)
"""
import torch
import torch.nn as nn
import comfy.utils
import comfy.ops
def conv(n_in, n_out, **kwargs):
return comfy.ops.disable_weight_init.Conv2d(n_in, n_out, 3, padding=1, **kwargs)
class Clamp... | |
10,305 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/taesd/taesd.py | 25,26 | 19,28 | forward | Block | 26,28 | 26,28 | class Block(nn.Module):
def __init__(self, n_in, n_out):
super().__init__()
self.conv = nn.Sequential(conv(n_in, n_out), nn.ReLU(), conv(n_out, n_out), nn.ReLU(), conv(n_out, n_out))
self.skip = comfy.ops.disable_weight_init.Conv2d(n_in, n_out, 1, bias=False) if n_in != n_out else nn.Identit... | class Block(nn.Module):
def __init__(self, n_in, n_out):
super().__init__()
self.conv = nn.Sequential(conv(n_in, n_out), nn.ReLU(), conv(n_out, n_out), nn.ReLU(), conv(n_out, n_out))
self.skip = comfy.ops.disable_weight_init.Conv2d(n_in, n_out, 1, bias=False) if n_in != n_out else nn.Identit... | return self.fuse(self.conv(x) + self.skip(x))
| return self.fuse(self.conv(x) + self.skip(x))
| 4 | 174 | 24 | 198 | #!/usr/bin/env python3
"""
Tiny AutoEncoder for Stable Diffusion
(DNN for encoding / decoding SD's latent space)
"""
import torch
import torch.nn as nn
import comfy.utils
import comfy.ops
def conv(n_in, n_out, **kwargs):
return comfy.ops.disable_weight_init.Conv2d(n_in, n_out, 3, padding=1, **kwargs)
class Clamp... | #!/usr/bin/env python3
"""
Tiny AutoEncoder for Stable Diffusion
(DNN for encoding / decoding SD's latent space)
"""
import torch
import torch.nn as nn
import comfy.utils
import comfy.ops
def conv(n_in, n_out, **kwargs):
return comfy.ops.disable_weight_init.Conv2d(n_in, n_out, 3, padding=1, **kwargs)
class Clamp... |
10,306 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/taesd/taesd.py | 16,17 | 15,19 | forward | Clamp | 17,19 | 17,19 | class Clamp(nn.Module):
def forward(self, x):
FILL_FUNC_BODY | class Clamp(nn.Module):
def forward(self, x):
FILL_FUNC_BODY | return torch.tanh(x / 3) * 3
| return torch.tanh(x / 3) * 3
| 6 | 28 | 20 | 48 | #!/usr/bin/env python3
"""
Tiny AutoEncoder for Stable Diffusion
(DNN for encoding / decoding SD's latent space)
"""
import torch
import torch.nn as nn
import comfy.utils
import comfy.ops
def conv(n_in, n_out, **kwargs):
return comfy.ops.disable_weight_init.Conv2d(n_in, n_out, 3, padding=1, **kwargs)
class Clamp... | #!/usr/bin/env python3
"""
Tiny AutoEncoder for Stable Diffusion
(DNN for encoding / decoding SD's latent space)
"""
import torch
import torch.nn as nn
import comfy.utils
import comfy.ops
def conv(n_in, n_out, **kwargs):
return comfy.ops.disable_weight_init.Conv2d(n_in, n_out, 3, padding=1, **kwargs)
class Clamp... |
10,307 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/taesd/taesd.py | 61,63 | 46,78 | scale_latents | TAESD | 64,66 | 63,66 | class TAESD(nn.Module):
latent_magnitude = 3
latent_shift = 0.5
def __init__(self, encoder_path=None, decoder_path=None):
"""Initialize pretrained TAESD on the given device from the given checkpoints."""
super().__init__()
self.taesd_encoder = Encoder()
self.taesd_decoder = ... | class TAESD(nn.Module):
latent_magnitude = 3
latent_shift = 0.5
def __init__(self, encoder_path=None, decoder_path=None):
"""Initialize pretrained TAESD on the given device from the given checkpoints."""
super().__init__()
self.taesd_encoder = Encoder()
self.taesd_decoder = ... | return x.div(2 * TAESD.latent_magnitude).add(TAESD.latent_shift).clamp(0, 1)
| """raw latents -> [0, 1]"""
return x.div(2 * TAESD.latent_magnitude).add(TAESD.latent_shift).clamp(0, 1)
| 5 | 441 | 43 | 484 | #!/usr/bin/env python3
"""
Tiny AutoEncoder for Stable Diffusion
(DNN for encoding / decoding SD's latent space)
"""
import torch
import torch.nn as nn
import comfy.utils
import comfy.ops
def conv(n_in, n_out, **kwargs):
return comfy.ops.disable_weight_init.Conv2d(n_in, n_out, 3, padding=1, **kwargs)
class Clamp... | #!/usr/bin/env python3
"""
Tiny AutoEncoder for Stable Diffusion
(DNN for encoding / decoding SD's latent space)
"""
import torch
import torch.nn as nn
import comfy.utils
import comfy.ops
def conv(n_in, n_out, **kwargs):
return comfy.ops.disable_weight_init.Conv2d(n_in, n_out, 3, padding=1, **kwargs)
class Clamp... |
10,309 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy/utils.py | 473,474 | 466,484 | update_absolute | ProgressBar | 474,482 | 474,482 | class ProgressBar:
def __init__(self, total):
global PROGRESS_BAR_HOOK
self.total = total
self.current = 0
self.hook = PROGRESS_BAR_HOOK
def update_absolute(self, value, total=None, preview=None):
FILL_FUNC_BODY def update(self, value):
self.update_absolute(self.curre... | class ProgressBar:
def __init__(self, total):
global PROGRESS_BAR_HOOK
self.total = total
self.current = 0
self.hook = PROGRESS_BAR_HOOK
def update_absolute(self, value, total=None, preview=None):
FILL_FUNC_BODY def update(self, value):
self.update_absolute(self.curre... | if total is not None:
self.total = total
if value > self.total:
value = self.total
self.current = value
if self.hook is not None:
self.hook(self.current, self.total, preview)
| if total is not None:
self.total = total
if value > self.total:
value = self.total
self.current = value
if self.hook is not None:
self.hook(self.current, self.total, preview)
| 26 | 109 | 73 | 182 | import torch
import math
import struct
import comfy.checkpoint_pickle
import safetensors.torch
import numpy as np
from PIL import Image
import logging
def load_torch_file(ckpt, safe_load=False, device=None):
if device is None:
device = torch.device("cpu")
if ckpt.lower().endswith(".safetensors"):
... | import torch
import math
import struct
import comfy.checkpoint_pickle
import safetensors.torch
import numpy as np
from PIL import Image
import logging
def load_torch_file(ckpt, safe_load=False, device=None):
if device is None:
device = torch.device("cpu")
if ckpt.lower().endswith(".safetensors"):
... |
10,311 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/chainner_models/architecture/DAT.py | 627,628 | 578,682 | forward | Adaptive_Channel_Attention | 632,682 | 628,682 | class Adaptive_Channel_Attention(nn.Module):
# The implementation builds on XCiT code https://github.com/facebookresearch/xcit
"""Adaptive Channel Self-Attention
Args:
dim (int): Number of input channels.
num_heads (int): Number of attention heads. Default: 6
qkv_bias (bool): If True... | class Adaptive_Channel_Attention(nn.Module):
# The implementation builds on XCiT code https://github.com/facebookresearch/xcit
"""Adaptive Channel Self-Attention
Args:
dim (int): Number of input channels.
num_heads (int): Number of attention heads. Default: 6
qkv_bias (bool): If True... | B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
qkv = qkv.permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2]
q = q.transpose(-2, -1)
k = k.transpose(-2, -1)
v = v.transpose(-2, -1)
v_ = v.reshape(B, C, N).co... | """
Input: x: (B, H*W, C), H, W
Output: x: (B, H*W, C)
"""
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
qkv = qkv.permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2]
q = q.transpose(-2, -1)
... | 160 | 721 | 680 | 1,401 | # pylint: skip-file
import math
import re
import numpy as np
import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from einops import rearrange
from einops.layers.torch import Rearrange
from torch import Tensor
from torch.nn import functional as F
from .timm.drop import DropPath
from .timm.we... | # pylint: skip-file
import math
import re
import numpy as np
import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from einops import rearrange
from einops.layers.torch import Rearrange
from torch import Tensor
from torch.nn import functional as F
from .timm.drop import DropPath
from .timm.we... |
10,314 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/chainner_models/architecture/DAT.py | 741,742 | 682,753 | forward | DATB | 746,753 | 742,753 | class DATB(nn.Module):
def __init__(
self,
dim,
num_heads,
reso=64,
split_size=[2, 4],
shift_size=[1, 2],
expansion_factor=4.0,
qkv_bias=False,
qk_scale=None,
drop=0.0,
attn_drop=0.0,
drop_path=0.0,
act_layer=nn.... | class DATB(nn.Module):
def __init__(
self,
dim,
num_heads,
reso=64,
split_size=[2, 4],
shift_size=[1, 2],
expansion_factor=4.0,
qkv_bias=False,
qk_scale=None,
drop=0.0,
attn_drop=0.0,
drop_path=0.0,
act_layer=nn.... | H, W = x_size
x = x + self.drop_path(self.attn(self.norm1(x), H, W))
x = x + self.drop_path(self.ffn(self.norm2(x), H, W))
return x
| """
Input: x: (B, H*W, C), x_size: (H, W)
Output: x: (B, H*W, C)
"""
H, W = x_size
x = x + self.drop_path(self.attn(self.norm1(x), H, W))
x = x + self.drop_path(self.ffn(self.norm2(x), H, W))
return x
| 20 | 613 | 79 | 692 | # pylint: skip-file
import math
import re
import numpy as np
import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from einops import rearrange
from einops.layers.torch import Rearrange
from torch import Tensor
from torch.nn import functional as F
from .timm.drop import DropPath
from .timm.we... | # pylint: skip-file
import math
import re
import numpy as np
import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from einops import rearrange
from einops.layers.torch import Rearrange
from torch import Tensor
from torch.nn import functional as F
from .timm.drop import DropPath
from .timm.we... |
10,315 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/chainner_models/architecture/DAT.py | 145,146 | 114,156 | forward | DynamicPosBias | 146,156 | 146,156 | class DynamicPosBias(nn.Module):
# The implementation builds on Crossformer code https://github.com/cheerss/CrossFormer/blob/main/models/crossformer.py
"""Dynamic Relative Position Bias.
Args:
dim (int): Number of input channels.
num_heads (int): Number of attention heads.
residual (... | class DynamicPosBias(nn.Module):
# The implementation builds on Crossformer code https://github.com/cheerss/CrossFormer/blob/main/models/crossformer.py
"""Dynamic Relative Position Bias.
Args:
dim (int): Number of input channels.
num_heads (int): Number of attention heads.
residual (... | if self.residual:
pos = self.pos_proj(biases) # 2Gh-1 * 2Gw-1, heads
pos = pos + self.pos1(pos)
pos = pos + self.pos2(pos)
pos = self.pos3(pos)
else:
pos = self.pos3(self.pos2(self.pos1(self.pos_proj(biases))))
return pos
| if self.residual:
pos = self.pos_proj(biases) # 2Gh-1 * 2Gw-1, heads
pos = pos + self.pos1(pos)
pos = pos + self.pos2(pos)
pos = self.pos3(pos)
else:
pos = self.pos3(self.pos2(self.pos1(self.pos_proj(biases))))
return pos
| 29 | 401 | 124 | 525 | # pylint: skip-file
import math
import re
import numpy as np
import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from einops import rearrange
from einops.layers.torch import Rearrange
from torch import Tensor
from torch.nn import functional as F
from .timm.drop import DropPath
from .timm.we... | # pylint: skip-file
import math
import re
import numpy as np
import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from einops import rearrange
from einops.layers.torch import Rearrange
from torch import Tensor
from torch.nn import functional as F
from .timm.drop import DropPath
from .timm.we... |
10,316 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/chainner_models/architecture/DAT.py | 830,831 | 753,850 | forward | ResidualGroup | 835,850 | 831,850 | class ResidualGroup(nn.Module):
"""ResidualGroup
Args:
dim (int): Number of input channels.
reso (int): Input resolution.
num_heads (int): Number of attention heads.
split_size (tuple(int)): Height and Width of spatial window.
expansion_factor (float): Ratio of ffn hidden... | class ResidualGroup(nn.Module):
"""ResidualGroup
Args:
dim (int): Number of input channels.
reso (int): Input resolution.
num_heads (int): Number of attention heads.
split_size (tuple(int)): Height and Width of spatial window.
expansion_factor (float): Ratio of ffn hidden... | H, W = x_size
res = x
for blk in self.blocks:
if self.use_chk:
x = checkpoint.checkpoint(blk, x, x_size)
else:
x = blk(x, x_size)
x = rearrange(x, "b (h w) c -> b c h w", h=H, w=W)
x = self.conv(x)
x = rearrange(x, "... | """
Input: x: (B, H*W, C), x_size: (H, W)
Output: x: (B, H*W, C)
"""
H, W = x_size
res = x
for blk in self.blocks:
if self.use_chk:
x = checkpoint.checkpoint(blk, x, x_size)
else:
x = blk(x, x_size)
x... | 59 | 977 | 165 | 1,142 | # pylint: skip-file
import math
import re
import numpy as np
import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from einops import rearrange
from einops.layers.torch import Rearrange
from torch import Tensor
from torch.nn import functional as F
from .timm.drop import DropPath
from .timm.we... | # pylint: skip-file
import math
import re
import numpy as np
import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from einops import rearrange
from einops.layers.torch import Rearrange
from torch import Tensor
from torch.nn import functional as F
from .timm.drop import DropPath
from .timm.we... |
10,317 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/chainner_models/architecture/DAT.py | 97,98 | 70,114 | forward | SGFN | 102,114 | 98,114 | class SGFN(nn.Module):
"""Spatial-Gate Feed-Forward Network.
Args:
in_features (int): Number of input channels.
hidden_features (int | None): Number of hidden channels. Default: None
out_features (int | None): Number of output channels. Default: None
act_layer (nn.Module): Activa... | class SGFN(nn.Module):
"""Spatial-Gate Feed-Forward Network.
Args:
in_features (int): Number of input channels.
hidden_features (int | None): Number of hidden channels. Default: None
out_features (int | None): Number of output channels. Default: None
act_layer (nn.Module): Activa... | x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.sg(x, H, W)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
| """
Input: x: (B, H*W, C), H, W
Output: x: (B, H*W, C)
"""
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.sg(x, H, W)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
| 25 | 359 | 96 | 455 | # pylint: skip-file
import math
import re
import numpy as np
import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from einops import rearrange
from einops.layers.torch import Rearrange
from torch import Tensor
from torch.nn import functional as F
from .timm.drop import DropPath
from .timm.we... | # pylint: skip-file
import math
import re
import numpy as np
import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from einops import rearrange
from einops.layers.torch import Rearrange
from torch import Tensor
from torch.nn import functional as F
from .timm.drop import DropPath
from .timm.we... |
10,318 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/chainner_models/architecture/DAT.py | 56,57 | 43,70 | forward | SpatialGate | 57,70 | 57,70 | class SpatialGate(nn.Module):
"""Spatial-Gate.
Args:
dim (int): Half of input channels.
"""
def __init__(self, dim):
super().__init__()
self.norm = nn.LayerNorm(dim)
self.conv = nn.Conv2d(
dim, dim, kernel_size=3, stride=1, padding=1, groups=dim
) # ... | class SpatialGate(nn.Module):
"""Spatial-Gate.
Args:
dim (int): Half of input channels.
"""
def __init__(self, dim):
super().__init__()
self.norm = nn.LayerNorm(dim)
self.conv = nn.Conv2d(
dim, dim, kernel_size=3, stride=1, padding=1, groups=dim
) # ... | # Split
x1, x2 = x.chunk(2, dim=-1)
B, N, C = x.shape
x2 = (
self.conv(self.norm(x2).transpose(1, 2).contiguous().view(B, C // 2, H, W))
.flatten(2)
.transpose(-1, -2)
.contiguous()
)
return x1 * x2
| # Split
x1, x2 = x.chunk(2, dim=-1)
B, N, C = x.shape
x2 = (
self.conv(self.norm(x2).transpose(1, 2).contiguous().view(B, C // 2, H, W))
.flatten(2)
.transpose(-1, -2)
.contiguous()
)
return x1 * x2
| 31 | 144 | 133 | 277 | # pylint: skip-file
import math
import re
import numpy as np
import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from einops import rearrange
from einops.layers.torch import Rearrange
from torch import Tensor
from torch.nn import functional as F
from .timm.drop import DropPath
from .timm.we... | # pylint: skip-file
import math
import re
import numpy as np
import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from einops import rearrange
from einops.layers.torch import Rearrange
from torch import Tensor
from torch.nn import functional as F
from .timm.drop import DropPath
from .timm.we... |
10,319 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/chainner_models/architecture/DAT.py | 228,229 | 156,293 | im2win | Spatial_Attention | 229,239 | 229,239 | class Spatial_Attention(nn.Module):
"""Spatial Window Self-Attention.
It supports rectangle window (containing square window).
Args:
dim (int): Number of input channels.
idx (int): The indentix of window. (0/1)
split_size (tuple(int)): Height and Width of spatial window.
dim_... | class Spatial_Attention(nn.Module):
"""Spatial Window Self-Attention.
It supports rectangle window (containing square window).
Args:
dim (int): Number of input channels.
idx (int): The indentix of window. (0/1)
split_size (tuple(int)): Height and Width of spatial window.
dim_... | B, N, C = x.shape
x = x.transpose(-2, -1).contiguous().view(B, C, H, W)
x = img2windows(x, self.H_sp, self.W_sp)
x = (
x.reshape(-1, self.H_sp * self.W_sp, self.num_heads, C // self.num_heads)
.permute(0, 2, 1, 3)
.contiguous()
)
return... | B, N, C = x.shape
x = x.transpose(-2, -1).contiguous().view(B, C, H, W)
x = img2windows(x, self.H_sp, self.W_sp)
x = (
x.reshape(-1, self.H_sp * self.W_sp, self.num_heads, C // self.num_heads)
.permute(0, 2, 1, 3)
.contiguous()
)
return... | 36 | 1,681 | 146 | 1,827 | # pylint: skip-file
import math
import re
import numpy as np
import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from einops import rearrange
from einops.layers.torch import Rearrange
from torch import Tensor
from torch.nn import functional as F
from .timm.drop import DropPath
from .timm.we... | # pylint: skip-file
import math
import re
import numpy as np
import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from einops import rearrange
from einops.layers.torch import Rearrange
from torch import Tensor
from torch.nn import functional as F
from .timm.drop import DropPath
from .timm.we... |
10,320 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/chainner_models/architecture/DAT.py | 891,892 | 873,897 | flops | UpsampleOneStep | 892,897 | 892,897 | class UpsampleOneStep(nn.Sequential):
"""UpsampleOneStep module (the difference with Upsample is that it always only has 1conv + 1pixelshuffle)
Used in lightweight SR to save parameters.
Args:
scale (int): Scale factor. Supported scales: 2^n and 3.
num_feat (int): Channel number of inter... | class UpsampleOneStep(nn.Sequential):
"""UpsampleOneStep module (the difference with Upsample is that it always only has 1conv + 1pixelshuffle)
Used in lightweight SR to save parameters.
Args:
scale (int): Scale factor. Supported scales: 2^n and 3.
num_feat (int): Channel number of inter... | h, w = self.input_resolution
flops = h * w * self.num_feat * 3 * 9
return flops
| h, w = self.input_resolution
flops = h * w * self.num_feat * 3 * 9
return flops
| 17 | 251 | 44 | 295 | # pylint: skip-file
import math
import re
import numpy as np
import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from einops import rearrange
from einops.layers.torch import Rearrange
from torch import Tensor
from torch.nn import functional as F
from .timm.drop import DropPath
from .timm.we... | # pylint: skip-file
import math
import re
import numpy as np
import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from einops import rearrange
from einops.layers.torch import Rearrange
from torch import Tensor
from torch.nn import functional as F
from .timm.drop import DropPath
from .timm.we... |
10,322 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/chainner_models/architecture/HAT.py | 632,633 | 539,643 | forward | AttenBlocks | 633,643 | 633,643 | class AttenBlocks(nn.Module):
"""A series of attention blocks for one RHAG.
Args:
dim (int): Number of input channels.
input_resolution (tuple[int]): Input resolution.
depth (int): Number of blocks.
num_heads (int): Number of attention heads.
window_size (int): Local wind... | class AttenBlocks(nn.Module):
"""A series of attention blocks for one RHAG.
Args:
dim (int): Number of input channels.
input_resolution (tuple[int]): Input resolution.
depth (int): Number of blocks.
num_heads (int): Number of attention heads.
window_size (int): Local wind... | for blk in self.blocks:
x = blk(x, x_size, params["rpi_sa"], params["attn_mask"])
x = self.overlap_attn(x, x_size, params["rpi_oca"])
if self.downsample is not None:
x = self.downsample(x)
return x
| for blk in self.blocks:
x = blk(x, x_size, params["rpi_sa"], params["attn_mask"])
x = self.overlap_attn(x, x_size, params["rpi_oca"])
if self.downsample is not None:
x = self.downsample(x)
return x
| 25 | 966 | 104 | 1,070 | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... |
10,323 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/chainner_models/architecture/HAT.py | 77,78 | 66,81 | forward | CAB | 78,81 | 78,81 | class CAB(nn.Module):
def __init__(self, num_feat, compress_ratio=3, squeeze_factor=30):
super(CAB, self).__init__()
self.cab = nn.Sequential(
nn.Conv2d(num_feat, num_feat // compress_ratio, 3, 1, 1),
nn.GELU(),
nn.Conv2d(num_feat // compress_ratio, num_feat, 3, ... | class CAB(nn.Module):
def __init__(self, num_feat, compress_ratio=3, squeeze_factor=30):
super(CAB, self).__init__()
self.cab = nn.Sequential(
nn.Conv2d(num_feat, num_feat // compress_ratio, 3, 1, 1),
nn.GELU(),
nn.Conv2d(num_feat // compress_ratio, num_feat, 3, ... | return self.cab(x)
| return self.cab(x)
| 2 | 177 | 14 | 191 | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... |
10,324 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/chainner_models/architecture/HAT.py | 61,62 | 44,66 | forward | ChannelAttention | 62,66 | 62,66 | class ChannelAttention(nn.Module):
"""Channel attention used in RCAN.
Args:
num_feat (int): Channel number of intermediate features.
squeeze_factor (int): Channel squeeze factor. Default: 16.
"""
def __init__(self, num_feat, squeeze_factor=16):
super(ChannelAttention, self).__in... | class ChannelAttention(nn.Module):
"""Channel attention used in RCAN.
Args:
num_feat (int): Channel number of intermediate features.
squeeze_factor (int): Channel squeeze factor. Default: 16.
"""
def __init__(self, num_feat, squeeze_factor=16):
super(ChannelAttention, self).__in... | y = self.attention(x)
return x * y
| y = self.attention(x)
return x * y
| 7 | 238 | 22 | 260 | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... |
10,325 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/chainner_models/architecture/HAT.py | 40,41 | 31,44 | forward | DropPath | 41,44 | 41,44 | class DropPath(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
From: https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/drop.py
"""
def __init__(self, drop_prob=None):
super(DropPath, self).__init__()
... | class DropPath(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
From: https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/drop.py
"""
def __init__(self, drop_prob=None):
super(DropPath, self).__init__()
... | return drop_path(x, self.drop_prob, self.training) # type: ignore
| return drop_path(x, self.drop_prob, self.training) # type: ignore
| 7 | 133 | 29 | 162 | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... |
10,326 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/chainner_models/architecture/HAT.py | 312,313 | 234,366 | forward | HAB | 313,366 | 313,366 | class HAB(nn.Module):
r"""Hybrid Attention Block.
Args:
dim (int): Number of input channels.
input_resolution (tuple[int]): Input resolution.
num_heads (int): Number of attention heads.
window_size (int): Window size.
shift_size (int): Shift size for SW-MSA.
mlp_r... | class HAB(nn.Module):
r"""Hybrid Attention Block.
Args:
dim (int): Number of input channels.
input_resolution (tuple[int]): Input resolution.
num_heads (int): Number of attention heads.
window_size (int): Window size.
shift_size (int): Shift size for SW-MSA.
mlp_r... | h, w = x_size
b, _, c = x.shape
# assert seq_len == h * w, "input feature has wrong size"
shortcut = x
x = self.norm1(x)
x = x.view(b, h, w, c)
# Conv_X
conv_x = self.conv_block(x.permute(0, 3, 1, 2))
conv_x = conv_x.permute(0, 2, 3, 1).contiguou... | h, w = x_size
b, _, c = x.shape
# assert seq_len == h * w, "input feature has wrong size"
shortcut = x
x = self.norm1(x)
x = x.view(b, h, w, c)
# Conv_X
conv_x = self.conv_block(x.permute(0, 3, 1, 2))
conv_x = conv_x.permute(0, 2, 3, 1).contiguou... | 192 | 928 | 681 | 1,609 | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... |
10,328 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/chainner_models/architecture/HAT.py | 98,99 | 81,107 | forward | Mlp | 99,107 | 99,107 | class Mlp(nn.Module):
def __init__(
self,
in_features,
hidden_features=None,
out_features=None,
act_layer=nn.GELU,
drop=0.0,
):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
... | class Mlp(nn.Module):
def __init__(
self,
in_features,
hidden_features=None,
out_features=None,
act_layer=nn.GELU,
drop=0.0,
):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
... | x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
| x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
| 17 | 183 | 66 | 249 | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... |
10,329 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/chainner_models/architecture/HAT.py | 457,458 | 405,539 | forward | OCAB | 458,539 | 458,539 | class OCAB(nn.Module):
# overlapping cross-attention block
def __init__(
self,
dim,
input_resolution,
window_size,
overlap_ratio,
num_heads,
qkv_bias=True,
qk_scale=None,
mlp_ratio=2,
norm_layer=nn.LayerNorm,
):
super()... | class OCAB(nn.Module):
# overlapping cross-attention block
def __init__(
self,
dim,
input_resolution,
window_size,
overlap_ratio,
num_heads,
qkv_bias=True,
qk_scale=None,
mlp_ratio=2,
norm_layer=nn.LayerNorm,
):
super()... | h, w = x_size
b, _, c = x.shape
shortcut = x
x = self.norm1(x)
x = x.view(b, h, w, c)
qkv = self.qkv(x).reshape(b, h, w, 3, c).permute(3, 0, 4, 1, 2) # 3, b, c, h, w
q = qkv[0].permute(0, 2, 3, 1) # b, h, w, c
kv = torch.cat((qkv[1], qkv[2]), dim=1) #... | h, w = x_size
b, _, c = x.shape
shortcut = x
x = self.norm1(x)
x = x.view(b, h, w, c)
qkv = self.qkv(x).reshape(b, h, w, 3, c).permute(3, 0, 4, 1, 2) # 3, b, c, h, w
q = qkv[0].permute(0, 2, 3, 1) # b, h, w, c
kv = torch.cat((qkv[1], qkv[2]), dim=1) #... | 330 | 596 | 1,260 | 1,856 | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... |
10,330 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/chainner_models/architecture/HAT.py | 780,781 | 747,787 | forward | PatchEmbed | 781,787 | 781,787 | class PatchEmbed(nn.Module):
r"""Image to Patch Embedding
Args:
img_size (int): Image size. Default: 224.
patch_size (int): Patch token size. Default: 4.
in_chans (int): Number of input image channels. Default: 3.
embed_dim (int): Number of linear projection output channels. Def... | class PatchEmbed(nn.Module):
r"""Image to Patch Embedding
Args:
img_size (int): Image size. Default: 224.
patch_size (int): Patch token size. Default: 4.
in_chans (int): Number of input image channels. Default: 3.
embed_dim (int): Number of linear projection output channels. Def... | x = x.flatten(2).transpose(1, 2) # b Ph*Pw c
if self.norm is not None:
x = self.norm(x)
return x
| x = x.flatten(2).transpose(1, 2) # b Ph*Pw c
if self.norm is not None:
x = self.norm(x)
return x
| 18 | 402 | 59 | 461 | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... |
10,331 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/chainner_models/architecture/HAT.py | 381,382 | 366,405 | forward | PatchMerging | 385,405 | 382,405 | class PatchMerging(nn.Module):
r"""Patch Merging Layer.
Args:
input_resolution (tuple[int]): Resolution of input feature.
dim (int): Number of input channels.
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
"""
def __init__(self, input_resolution, d... | class PatchMerging(nn.Module):
r"""Patch Merging Layer.
Args:
input_resolution (tuple[int]): Resolution of input feature.
dim (int): Number of input channels.
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
"""
def __init__(self, input_resolution, d... | h, w = self.input_resolution
b, seq_len, c = x.shape
assert seq_len == h * w, "input feature has wrong size"
assert h % 2 == 0 and w % 2 == 0, f"x size ({h}*{w}) are not even."
x = x.view(b, h, w, c)
x0 = x[:, 0::2, 0::2, :] # b h/2 w/2 c
x1 = x[:, 1::2, 0::2, ... | """
x: b, h*w, c
"""
h, w = self.input_resolution
b, seq_len, c = x.shape
assert seq_len == h * w, "input feature has wrong size"
assert h % 2 == 0 and w % 2 == 0, f"x size ({h}*{w}) are not even."
x = x.view(b, h, w, c)
x0 = x[:, 0::2, 0::2, :] ... | 119 | 211 | 332 | 543 | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... |
10,332 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/chainner_models/architecture/HAT.py | 815,816 | 787,824 | forward | PatchUnEmbed | 816,824 | 816,824 | class PatchUnEmbed(nn.Module):
r"""Image to Patch Unembedding
Args:
img_size (int): Image size. Default: 224.
patch_size (int): Patch token size. Default: 4.
in_chans (int): Number of input image channels. Default: 3.
embed_dim (int): Number of linear projection output channels.... | class PatchUnEmbed(nn.Module):
r"""Image to Patch Unembedding
Args:
img_size (int): Image size. Default: 224.
patch_size (int): Patch token size. Default: 4.
in_chans (int): Number of input image channels. Default: 3.
embed_dim (int): Number of linear projection output channels.... | x = (
x.transpose(1, 2)
.contiguous()
.view(x.shape[0], self.embed_dim, x_size[0], x_size[1])
) # b Ph*Pw c
return x
| x = (
x.transpose(1, 2)
.contiguous()
.view(x.shape[0], self.embed_dim, x_size[0], x_size[1])
) # b Ph*Pw c
return x
| 17 | 372 | 78 | 450 | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... |
10,333 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/chainner_models/architecture/HAT.py | 736,737 | 643,747 | forward | RHAG | 737,747 | 737,747 | class RHAG(nn.Module):
"""Residual Hybrid Attention Group (RHAG).
Args:
dim (int): Number of input channels.
input_resolution (tuple[int]): Input resolution.
depth (int): Number of blocks.
num_heads (int): Number of attention heads.
window_size (int): Local window size.
... | class RHAG(nn.Module):
"""Residual Hybrid Attention Group (RHAG).
Args:
dim (int): Number of input channels.
input_resolution (tuple[int]): Input resolution.
depth (int): Number of blocks.
num_heads (int): Number of attention heads.
window_size (int): Local window size.
... | return (
self.patch_embed(
self.conv(
self.patch_unembed(self.residual_group(x, x_size, params), x_size)
)
)
+ x
)
| return (
self.patch_embed(
self.conv(
self.patch_unembed(self.residual_group(x, x_size, params), x_size)
)
)
+ x
)
| 13 | 988 | 71 | 1,059 | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... |
10,334 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/chainner_models/architecture/HAT.py | 185,186 | 141,234 | forward | WindowAttention | 191,234 | 186,234 | class WindowAttention(nn.Module):
r"""Window based multi-head self attention (W-MSA) module with relative position bias.
It supports both of shifted and non-shifted window.
Args:
dim (int): Number of input channels.
window_size (tuple[int]): The height and width of the window.
num_he... | class WindowAttention(nn.Module):
r"""Window based multi-head self attention (W-MSA) module with relative position bias.
It supports both of shifted and non-shifted window.
Args:
dim (int): Number of input channels.
window_size (tuple[int]): The height and width of the window.
num_he... | b_, n, c = x.shape
qkv = (
self.qkv(x)
.reshape(b_, n, 3, self.num_heads, c // self.num_heads)
.permute(2, 0, 3, 1, 4)
)
q, k, v = (
qkv[0],
qkv[1],
qkv[2],
) # make torchscript happy (cannot use tensor as t... | """
Args:
x: input features with shape of (num_windows*b, n, c)
mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
"""
b_, n, c = x.shape
qkv = (
self.qkv(x)
.reshape(b_, n, 3, self.num_heads, c // self.num_heads)... | 133 | 670 | 560 | 1,230 | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... | # pylint: skip-file
# HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py
import math
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from .timm.helpers import to_2tuple
from .timm.weight_init import trunc_normal_
def drop_path(x, dro... |
10,335 | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI | /home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/chainner_models/architecture/LaMa.py | 510,511 | 509,519 | forward | ConcatTupleLayer | 511,519 | 511,519 | class ConcatTupleLayer(nn.Module):
def forward(self, x):
FILL_FUNC_BODY | class ConcatTupleLayer(nn.Module):
def forward(self, x):
FILL_FUNC_BODY | assert isinstance(x, tuple)
x_l, x_g = x
assert torch.is_tensor(x_l) or torch.is_tensor(x_g)
if not torch.is_tensor(x_g):
return x_l
return torch.cat(x, dim=1)
| assert isinstance(x, tuple)
x_l, x_g = x
assert torch.is_tensor(x_l) or torch.is_tensor(x_g)
if not torch.is_tensor(x_g):
return x_l
return torch.cat(x, dim=1)
| 19 | 31 | 92 | 123 | # pylint: skip-file
"""
Model adapted from advimman's lama project: https://github.com/advimman/lama
"""
# Fast Fourier Convolution NeurIPS 2020
# original implementation https://github.com/pkumivision/FFC/blob/main/model_zoo/ffc.py
# paper https://proceedings.neurips.cc/paper/2020/file/2fd5d41ec6cfab47e32164d5624269b... | # pylint: skip-file
"""
Model adapted from advimman's lama project: https://github.com/advimman/lama
"""
# Fast Fourier Convolution NeurIPS 2020
# original implementation https://github.com/pkumivision/FFC/blob/main/model_zoo/ffc.py
# paper https://proceedings.neurips.cc/paper/2020/file/2fd5d41ec6cfab47e32164d5624269b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.