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
10,563
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/nodes_photomaker.py
32,33
21,43
forward
MLP
33,43
33,43
class MLP(nn.Module): def __init__(self, in_dim, out_dim, hidden_dim, use_residual=True, operations=comfy.ops): super().__init__() if use_residual: assert in_dim == out_dim self.layernorm = operations.LayerNorm(in_dim) self.fc1 = operations.Linear(in_dim, hidden_dim) ...
class MLP(nn.Module): def __init__(self, in_dim, out_dim, hidden_dim, use_residual=True, operations=comfy.ops): super().__init__() if use_residual: assert in_dim == out_dim self.layernorm = operations.LayerNorm(in_dim) self.fc1 = operations.Linear(in_dim, hidden_dim) ...
residual = x x = self.layernorm(x) x = self.fc1(x) x = self.act_fn(x) x = self.fc2(x) if self.use_residual: x = x + residual return x
residual = x x = self.layernorm(x) x = self.fc1(x) x = self.act_fn(x) x = self.fc2(x) if self.use_residual: x = x + residual return x
24
172
84
256
import torch import torch.nn as nn import folder_paths import comfy.clip_model import comfy.clip_vision import comfy.ops # code for model from: https://github.com/TencentARC/PhotoMaker/blob/main/photomaker/model.py under Apache License Version 2.0 VISION_CONFIG_DICT = { "hidden_size": 1024, "image_size": 224, ...
import torch import torch.nn as nn import folder_paths import comfy.clip_model import comfy.clip_vision import comfy.ops # code for model from: https://github.com/TencentARC/PhotoMaker/blob/main/photomaker/model.py under Apache License Version 2.0 VISION_CONFIG_DICT = { "hidden_size": 1024, "image_size": 224, ...
10,564
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/nodes_photomaker.py
152,153
138,183
apply_photomaker
PhotoMakerEncode
153,183
153,183
class PhotoMakerEncode: @classmethod def INPUT_TYPES(s): return {"required": { "photomaker": ("PHOTOMAKER",), "image": ("IMAGE",), "clip": ("CLIP", ), "text": ("STRING", {"multiline": True, "dynamicPrompts": True, ...
class PhotoMakerEncode: @classmethod def INPUT_TYPES(s): return {"required": { "photomaker": ("PHOTOMAKER",), "image": ("IMAGE",), "clip": ("CLIP", ), "text": ("STRING", {"multiline": True, "dynamicPrompts": True, ...
special_token = "photomaker" pixel_values = comfy.clip_vision.clip_preprocess(image.to(photomaker.load_device)).float() try: index = text.split(" ").index(special_token) + 1 except ValueError: index = -1 tokens = clip.tokenize(text, return_word_ids=True) ...
special_token = "photomaker" pixel_values = comfy.clip_vision.clip_preprocess(image.to(photomaker.load_device)).float() try: index = text.split(" ").index(special_token) + 1 except ValueError: index = -1 tokens = clip.tokenize(text, return_word_ids=True) ...
98
188
434
622
import torch import torch.nn as nn import folder_paths import comfy.clip_model import comfy.clip_vision import comfy.ops # code for model from: https://github.com/TencentARC/PhotoMaker/blob/main/photomaker/model.py under Apache License Version 2.0 VISION_CONFIG_DICT = { "hidden_size": 1024, "image_size": 224, ...
import torch import torch.nn as nn import folder_paths import comfy.clip_model import comfy.clip_vision import comfy.ops # code for model from: https://github.com/TencentARC/PhotoMaker/blob/main/photomaker/model.py under Apache License Version 2.0 VISION_CONFIG_DICT = { "hidden_size": 1024, "image_size": 224, ...
10,565
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/nodes_photomaker.py
101,102
91,118
forward
PhotoMakerIDEncoder
102,118
102,118
class PhotoMakerIDEncoder(comfy.clip_model.CLIPVisionModelProjection): def __init__(self): self.load_device = comfy.model_management.text_encoder_device() offload_device = comfy.model_management.text_encoder_offload_device() dtype = comfy.model_management.text_encoder_dtype(self.load_device)...
class PhotoMakerIDEncoder(comfy.clip_model.CLIPVisionModelProjection): def __init__(self): self.load_device = comfy.model_management.text_encoder_device() offload_device = comfy.model_management.text_encoder_offload_device() dtype = comfy.model_management.text_encoder_dtype(self.load_device)...
b, num_inputs, c, h, w = id_pixel_values.shape id_pixel_values = id_pixel_values.view(b * num_inputs, c, h, w) shared_id_embeds = self.vision_model(id_pixel_values)[2] id_embeds = self.visual_projection(shared_id_embeds) id_embeds_2 = self.visual_projection_2(shared_id_embeds) ...
b, num_inputs, c, h, w = id_pixel_values.shape id_pixel_values = id_pixel_values.view(b * num_inputs, c, h, w) shared_id_embeds = self.vision_model(id_pixel_values)[2] id_embeds = self.visual_projection(shared_id_embeds) id_embeds_2 = self.visual_projection_2(shared_id_embeds) ...
48
243
280
523
import torch import torch.nn as nn import folder_paths import comfy.clip_model import comfy.clip_vision import comfy.ops # code for model from: https://github.com/TencentARC/PhotoMaker/blob/main/photomaker/model.py under Apache License Version 2.0 VISION_CONFIG_DICT = { "hidden_size": 1024, "image_size": 224, ...
import torch import torch.nn as nn import folder_paths import comfy.clip_model import comfy.clip_vision import comfy.ops # code for model from: https://github.com/TencentARC/PhotoMaker/blob/main/photomaker/model.py under Apache License Version 2.0 VISION_CONFIG_DICT = { "hidden_size": 1024, "image_size": 224, ...
10,566
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/nodes_photomaker.py
119,121
118,138
INPUT_TYPES
PhotoMakerLoader
121,123
121,123
class PhotoMakerLoader: @classmethod def INPUT_TYPES(s): FILL_FUNC_BODY RETURN_TYPES = ("PHOTOMAKER",) FUNCTION = "load_photomaker_model" CATEGORY = "_for_testing/photomaker" def load_photomaker_model(self, photomaker_model_name): photomaker_model_path = folder_paths.get_full_path("phot...
class PhotoMakerLoader: @classmethod def INPUT_TYPES(s): FILL_FUNC_BODY RETURN_TYPES = ("PHOTOMAKER",) FUNCTION = "load_photomaker_model" CATEGORY = "_for_testing/photomaker" def load_photomaker_model(self, photomaker_model_name): photomaker_model_path = folder_paths.get_full_path("phot...
return {"required": { "photomaker_model_name": (folder_paths.get_filename_list("photomaker"), )}}
return {"required": { "photomaker_model_name": (folder_paths.get_filename_list("photomaker"), )}}
6
240
38
278
import torch import torch.nn as nn import folder_paths import comfy.clip_model import comfy.clip_vision import comfy.ops # code for model from: https://github.com/TencentARC/PhotoMaker/blob/main/photomaker/model.py under Apache License Version 2.0 VISION_CONFIG_DICT = { "hidden_size": 1024, "image_size": 224, ...
import torch import torch.nn as nn import folder_paths import comfy.clip_model import comfy.clip_vision import comfy.ops # code for model from: https://github.com/TencentARC/PhotoMaker/blob/main/photomaker/model.py under Apache License Version 2.0 VISION_CONFIG_DICT = { "hidden_size": 1024, "image_size": 224, ...
10,567
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/nodes_rebatch.py
103,105
102,130
INPUT_TYPES
ImageRebatch
105,108
105,108
class ImageRebatch: @classmethod def INPUT_TYPES(s): FILL_FUNC_BODY RETURN_TYPES = ("IMAGE",) INPUT_IS_LIST = True OUTPUT_IS_LIST = (True, ) FUNCTION = "rebatch" CATEGORY = "image/batch" def rebatch(self, images, batch_size): batch_size = batch_size[0] output_list = []...
class ImageRebatch: @classmethod def INPUT_TYPES(s): FILL_FUNC_BODY RETURN_TYPES = ("IMAGE",) INPUT_IS_LIST = True OUTPUT_IS_LIST = (True, ) FUNCTION = "rebatch" CATEGORY = "image/batch" def rebatch(self, images, batch_size): batch_size = batch_size[0] output_list = []...
return {"required": { "images": ("IMAGE",), "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096}), }}
return {"required": { "images": ("IMAGE",), "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096}), }}
14
233
52
285
import torch class LatentRebatch: @classmethod def INPUT_TYPES(s): return {"required": { "latents": ("LATENT",), "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096}), }} RETURN_TYPES = ("LATENT",) INPUT_IS_LIST = True OUTPU...
import torch class LatentRebatch: @classmethod def INPUT_TYPES(s): return {"required": { "latents": ("LATENT",), "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096}), }} RETURN_TYPES = ("LATENT",) INPUT_IS_LIST = True OUTPU...
10,568
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/nodes_rebatch.py
56,57
3,102
rebatch
LatentRebatch
57,102
57,102
class LatentRebatch: @classmethod def INPUT_TYPES(s): return {"required": { "latents": ("LATENT",), "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096}), }} RETURN_TYPES = ("LATENT",) INPUT_IS_LIST = True OUTPUT_IS_LIST = (T...
class LatentRebatch: @classmethod def INPUT_TYPES(s): return {"required": { "latents": ("LATENT",), "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096}), }} RETURN_TYPES = ("LATENT",) INPUT_IS_LIST = True OUTPUT_IS_LIST = (T...
batch_size = batch_size[0] output_list = [] current_batch = (None, None, None) processed = 0 for i in range(len(latents)): # fetch new entry of list #samples, masks, indices = self.get_batch(latents, i) next_batch = self.get_batch(latents, i,...
batch_size = batch_size[0] output_list = [] current_batch = (None, None, None) processed = 0 for i in range(len(latents)): # fetch new entry of list #samples, masks, indices = self.get_batch(latents, i) next_batch = self.get_batch(latents, i,...
172
776
635
1,411
import torch class LatentRebatch: @classmethod def INPUT_TYPES(s): return {"required": { "latents": ("LATENT",), "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096}), }} RETURN_TYPES = ("LATENT",) INPUT_IS_LIST = True OUTPU...
import torch class LatentRebatch: @classmethod def INPUT_TYPES(s): return {"required": { "latents": ("LATENT",), "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096}), }} RETURN_TYPES = ("LATENT",) INPUT_IS_LIST = True OUTPU...
10,570
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/nodes_sag.py
115,116
96,164
attn_and_record
SelfAttentionGuidance
116,132
116,132
class SelfAttentionGuidance: @classmethod def INPUT_TYPES(s): return {"required": { "model": ("MODEL",), "scale": ("FLOAT", {"default": 0.5, "min": -2.0, "max": 5.0, "step": 0.1}), "blur_sigma": ("FLOAT", {"default": 2.0, "min": 0.0, "max": 10.0,...
class SelfAttentionGuidance: @classmethod def INPUT_TYPES(s): return {"required": { "model": ("MODEL",), "scale": ("FLOAT", {"default": 0.5, "min": -2.0, "max": 5.0, "step": 0.1}), "blur_sigma": ("FLOAT", {"default": 2.0, "min": 0.0, "max": 10.0,...
nonlocal attn_scores # if uncond, save the attention scores heads = extra_options["n_heads"] cond_or_uncond = extra_options["cond_or_uncond"] b = q.shape[0] // len(cond_or_uncond) if 1 in cond_or_uncond: uncond_index = cond_or_uncon...
nonlocal attn_scores # if uncond, save the attention scores heads = extra_options["n_heads"] cond_or_uncond = extra_options["cond_or_uncond"] b = q.shape[0] // len(cond_or_uncond) if 1 in cond_or_uncond: uncond_index = cond_or_uncon...
87
671
276
947
import torch from torch import einsum import torch.nn.functional as F import math from einops import rearrange, repeat import os from comfy.ldm.modules.attention import optimized_attention, _ATTN_PRECISION import comfy.samplers # from comfy/ldm/modules/attention.py # but modified to return attention scores as well as...
import torch from torch import einsum import torch.nn.functional as F import math from einops import rearrange, repeat import os from comfy.ldm.modules.attention import optimized_attention, _ATTN_PRECISION import comfy.samplers # from comfy/ldm/modules/attention.py # but modified to return attention scores as well as...
10,571
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/nodes_sdupscale.py
6,8
5,45
INPUT_TYPES
SD_4XUpscale_Conditioning
8,14
8,14
class SD_4XUpscale_Conditioning: @classmethod def INPUT_TYPES(s): FILL_FUNC_BODY RETURN_TYPES = ("CONDITIONING", "CONDITIONING", "LATENT") RETURN_NAMES = ("positive", "negative", "latent") FUNCTION = "encode" CATEGORY = "conditioning/upscale_diffusion" def encode(self, images, positive, ne...
class SD_4XUpscale_Conditioning: @classmethod def INPUT_TYPES(s): FILL_FUNC_BODY RETURN_TYPES = ("CONDITIONING", "CONDITIONING", "LATENT") RETURN_NAMES = ("positive", "negative", "latent") FUNCTION = "encode" CATEGORY = "conditioning/upscale_diffusion" def encode(self, images, positive, ne...
return {"required": { "images": ("IMAGE",), "positive": ("CONDITIONING",), "negative": ("CONDITIONING",), "scale_ratio": ("FLOAT", {"default": 4.0, "min": 0.0, "max": 10.0, "step": 0.01}), "no...
return {"required": { "images": ("IMAGE",), "positive": ("CONDITIONING",), "negative": ("CONDITIONING",), "scale_ratio": ("FLOAT", {"default": 4.0, "min": 0.0, "max": 10.0, "step": 0.01}), "no...
30
433
142
575
import torch import nodes import comfy.utils class SD_4XUpscale_Conditioning: @classmethod def INPUT_TYPES(s): FILL_FUNC_BODY RETURN_TYPES = ("CONDITIONING", "CONDITIONING", "LATENT") RETURN_NAMES = ("positive", "negative", "latent") FUNCTION = "encode" CATEGORY = "conditioning/upscale_diffusi...
import torch import nodes import comfy.utils class SD_4XUpscale_Conditioning: @classmethod def INPUT_TYPES(s): FILL_FUNC_BODY RETURN_TYPES = ("CONDITIONING", "CONDITIONING", "LATENT") RETURN_NAMES = ("positive", "negative", "latent") FUNCTION = "encode" CATEGORY = "conditioning/upscale_diffusi...
10,573
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/nodes_stable3d.py
116,117
98,139
encode
SV3D_Conditioning
117,139
117,139
class SV3D_Conditioning: @classmethod def INPUT_TYPES(s): return {"required": { "clip_vision": ("CLIP_VISION",), "init_image": ("IMAGE",), "vae": ("VAE",), "width": ("INT", {"default": 576, "min": 16, "max": nodes....
class SV3D_Conditioning: @classmethod def INPUT_TYPES(s): return {"required": { "clip_vision": ("CLIP_VISION",), "init_image": ("IMAGE",), "vae": ("VAE",), "width": ("INT", {"default": 576, "min": 16, "max": nodes....
output = clip_vision.encode_image(init_image) pooled = output.image_embeds.unsqueeze(0) pixels = comfy.utils.common_upscale(init_image.movedim(-1,1), width, height, "bilinear", "center").movedim(1,-1) encode_pixels = pixels[:,:,:,:3] t = vae.encode(encode_pixels) azimuth...
output = clip_vision.encode_image(init_image) pooled = output.image_embeds.unsqueeze(0) pixels = comfy.utils.common_upscale(init_image.movedim(-1,1), width, height, "bilinear", "center").movedim(1,-1) encode_pixels = pixels[:,:,:,:3] t = vae.encode(encode_pixels) azimuth...
77
351
369
720
import torch import nodes import comfy.utils def camera_embeddings(elevation, azimuth): elevation = torch.as_tensor([elevation]) azimuth = torch.as_tensor([azimuth]) embeddings = torch.stack( [ torch.deg2rad( (90 - elevation) - (90) ), # Zero123 ...
import torch import nodes import comfy.utils def camera_embeddings(elevation, azimuth): elevation = torch.as_tensor([elevation]) azimuth = torch.as_tensor([azimuth]) embeddings = torch.stack( [ torch.deg2rad( (90 - elevation) - (90) ), # Zero123 ...
10,574
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/nodes_stable3d.py
24,26
23,56
INPUT_TYPES
StableZero123_Conditioning
26,35
26,35
class StableZero123_Conditioning: @classmethod def INPUT_TYPES(s): FILL_FUNC_BODY RETURN_TYPES = ("CONDITIONING", "CONDITIONING", "LATENT") RETURN_NAMES = ("positive", "negative", "latent") FUNCTION = "encode" CATEGORY = "conditioning/3d_models" def encode(self, clip_vision, init_image, va...
class StableZero123_Conditioning: @classmethod def INPUT_TYPES(s): FILL_FUNC_BODY RETURN_TYPES = ("CONDITIONING", "CONDITIONING", "LATENT") RETURN_NAMES = ("positive", "negative", "latent") FUNCTION = "encode" CATEGORY = "conditioning/3d_models" def encode(self, clip_vision, init_image, va...
return {"required": { "clip_vision": ("CLIP_VISION",), "init_image": ("IMAGE",), "vae": ("VAE",), "width": ("INT", {"default": 256, "min": 16, "max": nodes.MAX_RESOLUTION, "step": 8}), "height...
return {"required": { "clip_vision": ("CLIP_VISION",), "init_image": ("IMAGE",), "vae": ("VAE",), "width": ("INT", {"default": 256, "min": 16, "max": nodes.MAX_RESOLUTION, "step": 8}), "height...
62
422
275
697
import torch import nodes import comfy.utils def camera_embeddings(elevation, azimuth): elevation = torch.as_tensor([elevation]) azimuth = torch.as_tensor([azimuth]) embeddings = torch.stack( [ torch.deg2rad( (90 - elevation) - (90) ), # Zero123 ...
import torch import nodes import comfy.utils def camera_embeddings(elevation, azimuth): elevation = torch.as_tensor([elevation]) azimuth = torch.as_tensor([azimuth]) embeddings = torch.stack( [ torch.deg2rad( (90 - elevation) - (90) ), # Zero123 ...
10,575
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/nodes_stable3d.py
77,78
56,98
encode
StableZero123_Conditioning_Batched
78,98
78,98
class StableZero123_Conditioning_Batched: @classmethod def INPUT_TYPES(s): return {"required": { "clip_vision": ("CLIP_VISION",), "init_image": ("IMAGE",), "vae": ("VAE",), "width": ("INT", {"default": 256, "min": ...
class StableZero123_Conditioning_Batched: @classmethod def INPUT_TYPES(s): return {"required": { "clip_vision": ("CLIP_VISION",), "init_image": ("IMAGE",), "vae": ("VAE",), "width": ("INT", {"default": 256, "min": ...
output = clip_vision.encode_image(init_image) pooled = output.image_embeds.unsqueeze(0) pixels = comfy.utils.common_upscale(init_image.movedim(-1,1), width, height, "bilinear", "center").movedim(1,-1) encode_pixels = pixels[:,:,:,:3] t = vae.encode(encode_pixels) cam_emb...
output = clip_vision.encode_image(init_image) pooled = output.image_embeds.unsqueeze(0) pixels = comfy.utils.common_upscale(init_image.movedim(-1,1), width, height, "bilinear", "center").movedim(1,-1) encode_pixels = pixels[:,:,:,:3] t = vae.encode(encode_pixels) cam_emb...
72
547
373
920
import torch import nodes import comfy.utils def camera_embeddings(elevation, azimuth): elevation = torch.as_tensor([elevation]) azimuth = torch.as_tensor([azimuth]) embeddings = torch.stack( [ torch.deg2rad( (90 - elevation) - (90) ), # Zero123 ...
import torch import nodes import comfy.utils def camera_embeddings(elevation, azimuth): elevation = torch.as_tensor([elevation]) azimuth = torch.as_tensor([azimuth]) embeddings = torch.stack( [ torch.deg2rad( (90 - elevation) - (90) ), # Zero123 ...
10,576
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/nodes_stable_cascade.py
42,43
24,51
generate
StableCascade_EmptyLatentImage
43,51
43,51
class StableCascade_EmptyLatentImage: def __init__(self, device="cpu"): self.device = device @classmethod def INPUT_TYPES(s): return {"required": { "width": ("INT", {"default": 1024, "min": 256, "max": nodes.MAX_RESOLUTION, "step": 8}), "height": ("INT", {"default": ...
class StableCascade_EmptyLatentImage: def __init__(self, device="cpu"): self.device = device @classmethod def INPUT_TYPES(s): return {"required": { "width": ("INT", {"default": 1024, "min": 256, "max": nodes.MAX_RESOLUTION, "step": 8}), "height": ("INT", {"default": ...
c_latent = torch.zeros([batch_size, 16, height // compression, width // compression]) b_latent = torch.zeros([batch_size, 4, height // 4, width // 4]) return ({ "samples": c_latent, }, { "samples": b_latent, })
c_latent = torch.zeros([batch_size, 16, height // compression, width // compression]) b_latent = torch.zeros([batch_size, 4, height // 4, width // 4]) return ({ "samples": c_latent, }, { "samples": b_latent, })
29
311
102
413
""" 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,577
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/nodes_stable_cascade.py
96,97
84,105
set_prior
StableCascade_StageB_Conditioning
97,105
97,105
class StableCascade_StageB_Conditioning: @classmethod def INPUT_TYPES(s): return {"required": { "conditioning": ("CONDITIONING",), "stage_c": ("LATENT",), }} RETURN_TYPES = ("CONDITIONING",) FUNCTION = "set_prior" CATEGORY = "condi...
class StableCascade_StageB_Conditioning: @classmethod def INPUT_TYPES(s): return {"required": { "conditioning": ("CONDITIONING",), "stage_c": ("LATENT",), }} RETURN_TYPES = ("CONDITIONING",) FUNCTION = "set_prior" CATEGORY = "condi...
c = [] for t in conditioning: d = t[1].copy() d['stable_cascade_prior'] = stage_c['samples'] n = [t[0], d] c.append(n) return (c, )
c = [] for t in conditioning: d = t[1].copy() d['stable_cascade_prior'] = stage_c['samples'] n = [t[0], d] c.append(n) return (c, )
21
139
77
216
""" 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,578
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/nodes_stable_cascade.py
68,69
51,84
generate
StableCascade_StageC_VAEEncode
69,84
69,84
class StableCascade_StageC_VAEEncode: def __init__(self, device="cpu"): self.device = device @classmethod def INPUT_TYPES(s): return {"required": { "image": ("IMAGE",), "vae": ("VAE", ), "compression": ("INT", {"default": 42, "min": 4, "max": 128, "step":...
class StableCascade_StageC_VAEEncode: def __init__(self, device="cpu"): self.device = device @classmethod def INPUT_TYPES(s): return {"required": { "image": ("IMAGE",), "vae": ("VAE", ), "compression": ("INT", {"default": 42, "min": 4, "max": 128, "step":...
width = image.shape[-2] height = image.shape[-3] out_width = (width // compression) * vae.downscale_ratio out_height = (height // compression) * vae.downscale_ratio s = comfy.utils.common_upscale(image.movedim(-1,1), out_width, out_height, "bicubic", "center").movedim(1,-1) ...
width = image.shape[-2] height = image.shape[-3] out_width = (width // compression) * vae.downscale_ratio out_height = (height // compression) * vae.downscale_ratio s = comfy.utils.common_upscale(image.movedim(-1,1), out_width, out_height, "bicubic", "center").movedim(1,-1) ...
53
214
226
440
""" 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,579
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/nodes_stable_cascade.py
121,122
105,135
generate
StableCascade_SuperResolutionControlnet
122,135
122,135
class StableCascade_SuperResolutionControlnet: def __init__(self, device="cpu"): self.device = device @classmethod def INPUT_TYPES(s): return {"required": { "image": ("IMAGE",), "vae": ("VAE", ), }} RETURN_TYPES = ("IMAGE", "LATENT", "LATENT") RETURN_...
class StableCascade_SuperResolutionControlnet: def __init__(self, device="cpu"): self.device = device @classmethod def INPUT_TYPES(s): return {"required": { "image": ("IMAGE",), "vae": ("VAE", ), }} RETURN_TYPES = ("IMAGE", "LATENT", "LATENT") RETURN_...
width = image.shape[-2] height = image.shape[-3] batch_size = image.shape[0] controlnet_input = vae.encode(image[:,:,:,:3]).movedim(1, -1) c_latent = torch.zeros([batch_size, 16, height // 16, width // 16]) b_latent = torch.zeros([batch_size, 4, height // 2, width // 2])...
width = image.shape[-2] height = image.shape[-3] batch_size = image.shape[0] controlnet_input = vae.encode(image[:,:,:,:3]).movedim(1, -1) c_latent = torch.zeros([batch_size, 16, height // 16, width // 16]) b_latent = torch.zeros([batch_size, 4, height // 2, width // 2])...
43
184
181
365
""" 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,581
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/nodes_tomesd.py
159,160
148,175
patch
TomePatchModel
160,175
160,175
class TomePatchModel: @classmethod def INPUT_TYPES(s): return {"required": { "model": ("MODEL",), "ratio": ("FLOAT", {"default": 0.3, "min": 0.0, "max": 1.0, "step": 0.01}), }} RETURN_TYPES = ("MODEL",) FUNCTION = "patch" CATEGORY ...
class TomePatchModel: @classmethod def INPUT_TYPES(s): return {"required": { "model": ("MODEL",), "ratio": ("FLOAT", {"default": 0.3, "min": 0.0, "max": 1.0, "step": 0.01}), }} RETURN_TYPES = ("MODEL",) FUNCTION = "patch" CATEGORY ...
self.u = None def tomesd_m(q, k, v, extra_options): #NOTE: In the reference code get_functions takes x (input of the transformer block) as the argument instead of q #however from my basic testing it seems that using q instead gives better results m, self.u = get_funct...
self.u = None def tomesd_m(q, k, v, extra_options): #NOTE: In the reference code get_functions takes x (input of the transformer block) as the argument instead of q #however from my basic testing it seems that using q instead gives better results m, self.u = get_funct...
64
145
204
349
#Taken from: https://github.com/dbolya/tomesd import torch from typing import Tuple, Callable import math def do_nothing(x: torch.Tensor, mode:str=None): return x def mps_gather_workaround(input, dim, index): if input.shape[-1] == 1: return torch.gather( input.unsqueeze(-1), ...
#Taken from: https://github.com/dbolya/tomesd import torch from typing import Tuple, Callable import math def do_nothing(x: torch.Tensor, mode:str=None): return x def mps_gather_workaround(input, dim, index): if input.shape[-1] == 1: return torch.gather( input.unsqueeze(-1), ...
10,582
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/nodes_upscale_model.py
28,30
27,68
INPUT_TYPES
ImageUpscaleWithModel
30,33
30,33
class ImageUpscaleWithModel: @classmethod def INPUT_TYPES(s): FILL_FUNC_BODY RETURN_TYPES = ("IMAGE",) FUNCTION = "upscale" CATEGORY = "image/upscaling" def upscale(self, upscale_model, image): device = model_management.get_torch_device() memory_required = model_management.modu...
class ImageUpscaleWithModel: @classmethod def INPUT_TYPES(s): FILL_FUNC_BODY RETURN_TYPES = ("IMAGE",) FUNCTION = "upscale" CATEGORY = "image/upscaling" def upscale(self, upscale_model, image): device = model_management.get_torch_device() memory_required = model_management.modu...
return {"required": { "upscale_model": ("UPSCALE_MODEL",), "image": ("IMAGE",), }}
return {"required": { "upscale_model": ("UPSCALE_MODEL",), "image": ("IMAGE",), }}
8
529
39
568
import os from comfy_extras.chainner_models import model_loading from comfy import model_management import torch import comfy.utils import folder_paths class UpscaleModelLoader: @classmethod def INPUT_TYPES(s): return {"required": { "model_name": (folder_paths.get_filename_list("upscale_models"), ), ...
import os from comfy_extras.chainner_models import model_loading from comfy import model_management import torch import comfy.utils import folder_paths class UpscaleModelLoader: @classmethod def INPUT_TYPES(s): return {"required": { "model_name": (folder_paths.get_filename_list("upscale_models"), ), ...
10,583
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/nodes_upscale_model.py
18,19
8,27
load_model
UpscaleModelLoader
19,27
19,27
class UpscaleModelLoader: @classmethod def INPUT_TYPES(s): return {"required": { "model_name": (folder_paths.get_filename_list("upscale_models"), ), }} RETURN_TYPES = ("UPSCALE_MODEL",) FUNCTION = "load_model" CATEGORY = "loaders" def load_model(self, model...
class UpscaleModelLoader: @classmethod def INPUT_TYPES(s): return {"required": { "model_name": (folder_paths.get_filename_list("upscale_models"), ), }} RETURN_TYPES = ("UPSCALE_MODEL",) FUNCTION = "load_model" CATEGORY = "loaders" def load_model(self, model...
model_path = folder_paths.get_full_path("upscale_models", model_name) sd = comfy.utils.load_torch_file(model_path, safe_load=True) if "module.layers.0.residual_group.blocks.0.norm1.weight" in sd: sd = comfy.utils.state_dict_prefix_replace(sd, {"module.":""}) out = model_loadi...
model_path = folder_paths.get_full_path("upscale_models", model_name) sd = comfy.utils.load_torch_file(model_path, safe_load=True) if "module.layers.0.residual_group.blocks.0.norm1.weight" in sd: sd = comfy.utils.state_dict_prefix_replace(sd, {"module.":""}) out = model_loadi...
22
124
141
265
import os from comfy_extras.chainner_models import model_loading from comfy import model_management import torch import comfy.utils import folder_paths class UpscaleModelLoader: @classmethod def INPUT_TYPES(s): return {"required": { "model_name": (folder_paths.get_filename_list("upscale_models"), ), ...
import os from comfy_extras.chainner_models import model_loading from comfy import model_management import torch import comfy.utils import folder_paths class UpscaleModelLoader: @classmethod def INPUT_TYPES(s): return {"required": { "model_name": (folder_paths.get_filename_list("upscale_models"), ), ...
10,584
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/nodes_video_model.py
10,12
9,25
INPUT_TYPES
ImageOnlyCheckpointLoader
12,14
12,14
class ImageOnlyCheckpointLoader: @classmethod def INPUT_TYPES(s): FILL_FUNC_BODY RETURN_TYPES = ("MODEL", "CLIP_VISION", "VAE") FUNCTION = "load_checkpoint" CATEGORY = "loaders/video_models" def load_checkpoint(self, ckpt_name, output_vae=True, output_clip=True): ckpt_path = folder_path...
class ImageOnlyCheckpointLoader: @classmethod def INPUT_TYPES(s): FILL_FUNC_BODY RETURN_TYPES = ("MODEL", "CLIP_VISION", "VAE") FUNCTION = "load_checkpoint" CATEGORY = "loaders/video_models" def load_checkpoint(self, ckpt_name, output_vae=True, output_clip=True): ckpt_path = folder_path...
return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"), ), }}
return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"), ), }}
7
225
33
258
import nodes import torch import comfy.utils import comfy.sd import folder_paths import comfy_extras.nodes_model_merging class ImageOnlyCheckpointLoader: @classmethod def INPUT_TYPES(s): FILL_FUNC_BODY RETURN_TYPES = ("MODEL", "CLIP_VISION", "VAE") FUNCTION = "load_checkpoint" CATEGORY = "loaders/...
import nodes import torch import comfy.utils import comfy.sd import folder_paths import comfy_extras.nodes_model_merging class ImageOnlyCheckpointLoader: @classmethod def INPUT_TYPES(s): FILL_FUNC_BODY RETURN_TYPES = ("MODEL", "CLIP_VISION", "VAE") FUNCTION = "load_checkpoint" CATEGORY = "loaders/...
10,585
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/nodes_video_model.py
120,121
109,124
save
ImageOnlyCheckpointSave
121,124
121,124
class ImageOnlyCheckpointSave(comfy_extras.nodes_model_merging.CheckpointSave): CATEGORY = "_for_testing" @classmethod def INPUT_TYPES(s): return {"required": { "model": ("MODEL",), "clip_vision": ("CLIP_VISION",), "vae": ("VAE",), ...
class ImageOnlyCheckpointSave(comfy_extras.nodes_model_merging.CheckpointSave): CATEGORY = "_for_testing" @classmethod def INPUT_TYPES(s): return {"required": { "model": ("MODEL",), "clip_vision": ("CLIP_VISION",), "vae": ("VAE",), ...
comfy_extras.nodes_model_merging.save_checkpoint(model, clip_vision=clip_vision, vae=vae, filename_prefix=filename_prefix, output_dir=self.output_dir, prompt=prompt, extra_pnginfo=extra_pnginfo) return {}
comfy_extras.nodes_model_merging.save_checkpoint(model, clip_vision=clip_vision, vae=vae, filename_prefix=filename_prefix, output_dir=self.output_dir, prompt=prompt, extra_pnginfo=extra_pnginfo) return {}
9
192
77
269
import nodes import torch import comfy.utils import comfy.sd import folder_paths import comfy_extras.nodes_model_merging class ImageOnlyCheckpointLoader: @classmethod def INPUT_TYPES(s): return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"), ), ...
import nodes import torch import comfy.utils import comfy.sd import folder_paths import comfy_extras.nodes_model_merging class ImageOnlyCheckpointLoader: @classmethod def INPUT_TYPES(s): return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"), ), ...
10,586
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/nodes_video_model.py
26,28
25,58
INPUT_TYPES
SVD_img2vid_Conditioning
28,38
28,38
class SVD_img2vid_Conditioning: @classmethod def INPUT_TYPES(s): FILL_FUNC_BODY RETURN_TYPES = ("CONDITIONING", "CONDITIONING", "LATENT") RETURN_NAMES = ("positive", "negative", "latent") FUNCTION = "encode" CATEGORY = "conditioning/video_models" def encode(self, clip_vision, init_image, v...
class SVD_img2vid_Conditioning: @classmethod def INPUT_TYPES(s): FILL_FUNC_BODY RETURN_TYPES = ("CONDITIONING", "CONDITIONING", "LATENT") RETURN_NAMES = ("positive", "negative", "latent") FUNCTION = "encode" CATEGORY = "conditioning/video_models" def encode(self, clip_vision, init_image, v...
return {"required": { "clip_vision": ("CLIP_VISION",), "init_image": ("IMAGE",), "vae": ("VAE",), "width": ("INT", {"default": 1024, "min": 16, "max": nodes.MAX_RESOLUTION, "step": 8}), "heigh...
return {"required": { "clip_vision": ("CLIP_VISION",), "init_image": ("IMAGE",), "vae": ("VAE",), "width": ("INT", {"default": 1024, "min": 16, "max": nodes.MAX_RESOLUTION, "step": 8}), "heigh...
64
470
287
757
import nodes import torch import comfy.utils import comfy.sd import folder_paths import comfy_extras.nodes_model_merging class ImageOnlyCheckpointLoader: @classmethod def INPUT_TYPES(s): return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"), ), ...
import nodes import torch import comfy.utils import comfy.sd import folder_paths import comfy_extras.nodes_model_merging class ImageOnlyCheckpointLoader: @classmethod def INPUT_TYPES(s): return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"), ), ...
10,587
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/nodes_video_model.py
69,70
58,82
patch
VideoLinearCFGGuidance
70,82
70,82
class VideoLinearCFGGuidance: @classmethod def INPUT_TYPES(s): return {"required": { "model": ("MODEL",), "min_cfg": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 100.0, "step":0.5, "round": 0.01}), }} RETURN_TYPES = ("MODEL",) FUNCTION...
class VideoLinearCFGGuidance: @classmethod def INPUT_TYPES(s): return {"required": { "model": ("MODEL",), "min_cfg": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 100.0, "step":0.5, "round": 0.01}), }} RETURN_TYPES = ("MODEL",) FUNCTION...
def linear_cfg(args): cond = args["cond"] uncond = args["uncond"] cond_scale = args["cond_scale"] scale = torch.linspace(min_cfg, cond_scale, cond.shape[0], device=cond.device).reshape((cond.shape[0], 1, 1, 1)) return uncond + scale * (cond - uncond) ...
def linear_cfg(args): cond = args["cond"] uncond = args["uncond"] cond_scale = args["cond_scale"] scale = torch.linspace(min_cfg, cond_scale, cond.shape[0], device=cond.device).reshape((cond.shape[0], 1, 1, 1)) return uncond + scale * (cond - uncond) ...
35
162
150
312
import nodes import torch import comfy.utils import comfy.sd import folder_paths import comfy_extras.nodes_model_merging class ImageOnlyCheckpointLoader: @classmethod def INPUT_TYPES(s): return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"), ), ...
import nodes import torch import comfy.utils import comfy.sd import folder_paths import comfy_extras.nodes_model_merging class ImageOnlyCheckpointLoader: @classmethod def INPUT_TYPES(s): return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"), ), ...
10,588
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/comfy_extras/nodes_video_model.py
83,85
82,109
INPUT_TYPES
VideoTriangleCFGGuidance
85,88
85,88
class VideoTriangleCFGGuidance: @classmethod def INPUT_TYPES(s): FILL_FUNC_BODY RETURN_TYPES = ("MODEL",) FUNCTION = "patch" CATEGORY = "sampling/video_models" def patch(self, model, min_cfg): def linear_cfg(args): cond = args["cond"] uncond = args["uncond"] ...
class VideoTriangleCFGGuidance: @classmethod def INPUT_TYPES(s): FILL_FUNC_BODY RETURN_TYPES = ("MODEL",) FUNCTION = "patch" CATEGORY = "sampling/video_models" def patch(self, model, min_cfg): def linear_cfg(args): cond = args["cond"] uncond = args["uncond"] ...
return {"required": { "model": ("MODEL",), "min_cfg": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 100.0, "step":0.5, "round": 0.01}), }}
return {"required": { "model": ("MODEL",), "min_cfg": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 100.0, "step":0.5, "round": 0.01}), }}
17
280
75
355
import nodes import torch import comfy.utils import comfy.sd import folder_paths import comfy_extras.nodes_model_merging class ImageOnlyCheckpointLoader: @classmethod def INPUT_TYPES(s): return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"), ), ...
import nodes import torch import comfy.utils import comfy.sd import folder_paths import comfy_extras.nodes_model_merging class ImageOnlyCheckpointLoader: @classmethod def INPUT_TYPES(s): return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"), ), ...
10,589
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/cuda_malloc.py
7,8
1,91
get_gpu_names
8,45
8,45
import os import importlib.util from comfy.cli_args import args import subprocess #Can't use pytorch to get the GPU names because the cuda malloc has to be set before the first import. def get_gpu_names(): FILL_FUNC_BODYblacklist = {"GeForce GTX TITAN X", "GeForce GTX 980", "GeForce GTX 970", "GeForce GTX 960", "GeFor...
import os import importlib.util from comfy.cli_args import args import subprocess #Can't use pytorch to get the GPU names because the cuda malloc has to be set before the first import. def get_gpu_names(): FILL_FUNC_BODYblacklist = {"GeForce GTX TITAN X", "GeForce GTX 980", "GeForce GTX 970", "GeForce GTX 960", "GeFor...
if os.name == 'nt': import ctypes # Define necessary C structures and types class DISPLAY_DEVICEA(ctypes.Structure): _fields_ = [ ('cb', ctypes.c_ulong), ('DeviceName', ctypes.c_char * 32), ('DeviceString', ctypes.c_char * 128), ...
if os.name == 'nt': import ctypes # Define necessary C structures and types class DISPLAY_DEVICEA(ctypes.Structure): _fields_ = [ ('cb', ctypes.c_ulong), ('DeviceName', ctypes.c_char * 32), ('DeviceString', ctypes.c_char * 128), ...
95
884
448
1,332
import os import importlib.util from comfy.cli_args import args import subprocess #Can't use pytorch to get the GPU names because the cuda malloc has to be set before the first import. def get_gpu_names(): FILL_FUNC_BODYblacklist = {"GeForce GTX TITAN X", "GeForce GTX 980", "GeForce GTX 970", "GeForce GTX 960", "GeFor...
import os import importlib.util from comfy.cli_args import args import subprocess #Can't use pytorch to get the GPU names because the cuda malloc has to be set before the first import. def get_gpu_names(): FILL_FUNC_BODYblacklist = {"GeForce GTX TITAN X", "GeForce GTX 980", "GeForce GTX 970", "GeForce GTX 960", "GeFor...
10,590
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/custom_nodes/example_node.py.example
83,84
1,111
test
Example
84,94
84,94
class Example: """ A example node Class methods ------------- INPUT_TYPES (dict): Tell the main program input parameters of nodes. IS_CHANGED: optional method to control when the node is re executed. Attributes ---------- RETURN_TYPES (`tuple`): The type o...
class Example: """ A example node Class methods ------------- INPUT_TYPES (dict): Tell the main program input parameters of nodes. IS_CHANGED: optional method to control when the node is re executed. Attributes ---------- RETURN_TYPES (`tuple`): The type o...
if print_to_screen == "enable": print(f"""Your input contains: string_field aka input text: {string_field} int_field: {int_field} float_field: {float_field} """) #do some processing on the image, in this example I just invert it ...
if print_to_screen == "enable": print(f"""Your input contains: string_field aka input text: {string_field} int_field: {int_field} float_field: {float_field} """) #do some processing on the image, in this example I just invert it ...
37
1,262
106
1,368
class Example: """ A example node Class methods ------------- INPUT_TYPES (dict): Tell the main program input parameters of nodes. IS_CHANGED: optional method to control when the node is re executed. Attributes ---------- RETURN_TYPES (`tuple`): The type o...
class Example: """ A example node Class methods ------------- INPUT_TYPES (dict): Tell the main program input parameters of nodes. IS_CHANGED: optional method to control when the node is re executed. Attributes ---------- RETURN_TYPES (`tuple`): The type o...
10,592
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/execution.py
330,331
271,404
execute
PromptExecutor
331,404
331,404
class PromptExecutor: def __init__(self, server): self.server = server self.reset() def reset(self): self.outputs = {} self.object_storage = {} self.outputs_ui = {} self.status_messages = [] self.success = True self.old_prompt = {} def add_me...
class PromptExecutor: def __init__(self, server): self.server = server self.reset() def reset(self): self.outputs = {} self.object_storage = {} self.outputs_ui = {} self.status_messages = [] self.success = True self.old_prompt = {} def add_me...
nodes.interrupt_processing(False) if "client_id" in extra_data: self.server.client_id = extra_data["client_id"] else: self.server.client_id = None self.status_messages = [] self.add_message("execution_start", { "prompt_id": prompt_id}, broadcast=False) ...
nodes.interrupt_processing(False) if "client_id" in extra_data: self.server.client_id = extra_data["client_id"] else: self.server.client_id = None self.status_messages = [] self.add_message("execution_start", { "prompt_id": prompt_id}, broadcast=False) ...
242
632
905
1,537
import sys import copy import logging import threading import heapq import traceback import inspect from typing import List, Literal, NamedTuple, Optional import torch import nodes import comfy.model_management def get_input_data(inputs, class_def, unique_id, outputs={}, prompt={}, extra_data={}): valid_inputs =...
import sys import copy import logging import threading import heapq import traceback import inspect from typing import List, Literal, NamedTuple, Optional import torch import nodes import comfy.model_management def get_input_data(inputs, class_def, unique_id, outputs={}, prompt={}, extra_data={}): valid_inputs =...
10,593
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/execution.py
731,732
713,836
get
PromptQueue
732,744
732,744
class PromptQueue: def __init__(self, server): self.server = server self.mutex = threading.RLock() self.not_empty = threading.Condition(self.mutex) self.task_counter = 0 self.queue = [] self.currently_running = {} self.history = {} self.flags = {} ...
class PromptQueue: def __init__(self, server): self.server = server self.mutex = threading.RLock() self.not_empty = threading.Condition(self.mutex) self.task_counter = 0 self.queue = [] self.currently_running = {} self.history = {} self.flags = {} ...
with self.not_empty: while len(self.queue) == 0: self.not_empty.wait(timeout=timeout) if timeout is not None and len(self.queue) == 0: return None item = heapq.heappop(self.queue) i = self.task_counter self.curre...
with self.not_empty: while len(self.queue) == 0: self.not_empty.wait(timeout=timeout) if timeout is not None and len(self.queue) == 0: return None item = heapq.heappop(self.queue) i = self.task_counter self.curre...
34
1,008
139
1,147
import sys import copy import logging import threading import heapq import traceback import inspect from typing import List, Literal, NamedTuple, Optional import torch import nodes import comfy.model_management def get_input_data(inputs, class_def, unique_id, outputs={}, prompt={}, extra_data={}): valid_inputs =...
import sys import copy import logging import threading import heapq import traceback import inspect from typing import List, Literal, NamedTuple, Optional import torch import nodes import comfy.model_management def get_input_data(inputs, class_def, unique_id, outputs={}, prompt={}, extra_data={}): valid_inputs =...
10,595
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/new_updater.py
7,8
1,36
update_windows_updater
8,36
8,36
import os import shutil base_path = os.path.dirname(os.path.realpath(__file__)) def update_windows_updater(): FILL_FUNC_BODY
import os import shutil base_path = os.path.dirname(os.path.realpath(__file__)) def update_windows_updater(): FILL_FUNC_BODY
top_path = os.path.dirname(base_path) updater_path = os.path.join(base_path, ".ci/update_windows/update.py") bat_path = os.path.join(base_path, ".ci/update_windows/update_comfyui.bat") dest_updater_path = os.path.join(top_path, "update/update.py") dest_bat_path = os.path.join(top_path, "update/upda...
top_path = os.path.dirname(base_path) updater_path = os.path.join(base_path, ".ci/update_windows/update.py") bat_path = os.path.join(base_path, ".ci/update_windows/update_comfyui.bat") dest_updater_path = os.path.join(top_path, "update/update.py") dest_bat_path = os.path.join(top_path, "update/upda...
74
52
436
488
import os import shutil base_path = os.path.dirname(os.path.realpath(__file__)) def update_windows_updater(): FILL_FUNC_BODY
import os import shutil base_path = os.path.dirname(os.path.realpath(__file__)) def update_windows_updater(): FILL_FUNC_BODY
10,596
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/node_helpers.py
3,4
1,26
conditioning_set_values
4,13
4,13
from PIL import Image, ImageFile, UnidentifiedImageError def conditioning_set_values(conditioning, values={}): FILL_FUNC_BODYdef open_image(path): prev_value = None try: img = Image.open(path) except (UnidentifiedImageError, ValueError): #PIL issues #4472 and #2445 prev_value = ImageFile.L...
from PIL import Image, ImageFile, UnidentifiedImageError def conditioning_set_values(conditioning, values={}): FILL_FUNC_BODYdef open_image(path): prev_value = None try: img = Image.open(path) except (UnidentifiedImageError, ValueError): #PIL issues #4472 and #2445 prev_value = ImageFile.L...
c = [] for t in conditioning: n = [t[0], t[1].copy()] for k in values: n[1][k] = values[k] c.append(n) return c
c = [] for t in conditioning: n = [t[0], t[1].copy()] for k in values: n[1][k] = values[k] c.append(n) return c
21
183
71
254
from PIL import Image, ImageFile, UnidentifiedImageError def conditioning_set_values(conditioning, values={}): FILL_FUNC_BODYdef open_image(path): prev_value = None try: img = Image.open(path) except (UnidentifiedImageError, ValueError): #PIL issues #4472 and #2445 prev_value = ImageFile.L...
from PIL import Image, ImageFile, UnidentifiedImageError def conditioning_set_values(conditioning, values={}): FILL_FUNC_BODYdef open_image(path): prev_value = None try: img = Image.open(path) except (UnidentifiedImageError, ValueError): #PIL issues #4472 and #2445 prev_value = ImageFile.L...
10,597
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI
/home/hieuvd/dung_repo/raw/stars_01/comfyanonymous_ComfyUI/ComfyUI/script_examples/basic_api_example.py
103,104
1,121
queue_prompt
104,110
104,110
import json from urllib import request, parse import random #This is the ComfyUI api prompt format. #If you want it for a specific workflow you can "enable dev mode options" #in the settings of the UI (gear beside the "Queue Size: ") this will enable #a button on the UI to save workflows in api format. #keep in mind...
import json from urllib import request, parse import random #This is the ComfyUI api prompt format. #If you want it for a specific workflow you can "enable dev mode options" #in the settings of the UI (gear beside the "Queue Size: ") this will enable #a button on the UI to save workflows in api format. #keep in mind...
p = {"prompt": prompt} data = json.dumps(p).encode('utf-8') req = request.Request("http://127.0.0.1:8188/prompt", data=data) request.urlopen(req)
p = {"prompt": prompt} data = json.dumps(p).encode('utf-8') req = request.Request("http://127.0.0.1:8188/prompt", data=data) request.urlopen(req)
12
766
76
842
import json from urllib import request, parse import random #This is the ComfyUI api prompt format. #If you want it for a specific workflow you can "enable dev mode options" #in the settings of the UI (gear beside the "Queue Size: ") this will enable #a button on the UI to save workflows in api format. #keep in mind...
import json from urllib import request, parse import random #This is the ComfyUI api prompt format. #If you want it for a specific workflow you can "enable dev mode options" #in the settings of the UI (gear beside the "Queue Size: ") this will enable #a button on the UI to save workflows in api format. #keep in mind...
11,999
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/linear_models/bayesian_regression.py
276,277
167,303
predict
BayesianLinearRegressionKnownVariance
291,303
277,303
class BayesianLinearRegressionKnownVariance: def __init__(self, mu=0, sigma=1, V=None, fit_intercept=True): r""" Bayesian linear regression model with known error variance and conjugate Gaussian prior on model parameters. Notes ----- Uses a conjugate Gaussian prior o...
class BayesianLinearRegressionKnownVariance: def __init__(self, mu=0, sigma=1, V=None, fit_intercept=True): r""" Bayesian linear regression model with known error variance and conjugate Gaussian prior on model parameters. Notes ----- Uses a conjugate Gaussian prior o...
# convert X to a design matrix if we're fitting an intercept if self.fit_intercept: X = np.c_[np.ones(X.shape[0]), X] I = np.eye(X.shape[0]) # noqa: E741 mu = X @ self.posterior["b"].mean cov = X @ self.posterior["b"].cov @ X.T + I # MAP estimate for y corr...
""" Return the MAP prediction for the targets associated with `X`. Parameters ---------- X : :py:class:`ndarray <numpy.ndarray>` of shape `(Z, M)` A dataset consisting of `Z` new examples, each of dimension `M`. Returns ------- y_pred : :py:c...
60
1,381
173
1,554
"""A module of Bayesian linear regression models.""" import numpy as np import scipy.stats as stats from numpy_ml.utils.testing import is_number, is_symmetric_positive_definite class BayesianLinearRegressionUnknownVariance: def __init__(self, alpha=1, beta=2, mu=0, V=None, fit_intercept=True): r""" ...
"""A module of Bayesian linear regression models.""" import numpy as np import scipy.stats as stats from numpy_ml.utils.testing import is_number, is_symmetric_positive_definite class BayesianLinearRegressionUnknownVariance: def __init__(self, alpha=1, beta=2, mu=0, V=None, fit_intercept=True): r""" ...
12,000
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/linear_models/bayesian_regression.py
139,140
8,167
predict
BayesianLinearRegressionUnknownVariance
153,167
140,167
class BayesianLinearRegressionUnknownVariance: def __init__(self, alpha=1, beta=2, mu=0, V=None, fit_intercept=True): r""" Bayesian linear regression model with unknown variance. Assumes a conjugate normal-inverse-gamma joint prior on the model parameters and error variance. ...
class BayesianLinearRegressionUnknownVariance: def __init__(self, alpha=1, beta=2, mu=0, V=None, fit_intercept=True): r""" Bayesian linear regression model with unknown variance. Assumes a conjugate normal-inverse-gamma joint prior on the model parameters and error variance. ...
# convert X to a design matrix if we're fitting an intercept if self.fit_intercept: X = np.c_[np.ones(X.shape[0]), X] I = np.eye(X.shape[0]) # noqa: E741 mu = X @ self.posterior["b | sigma**2"].mean cov = X @ self.posterior["b | sigma**2"].cov @ X.T + I # M...
""" Return the MAP prediction for the targets associated with `X`. Parameters ---------- X : :py:class:`ndarray <numpy.ndarray>` of shape `(Z, M)` A dataset consisting of `Z` new examples, each of dimension `M`. Returns ------- y_pred : :py:c...
62
1,696
182
1,878
"""A module of Bayesian linear regression models.""" import numpy as np import scipy.stats as stats from numpy_ml.utils.testing import is_number, is_symmetric_positive_definite class BayesianLinearRegressionUnknownVariance: def __init__(self, alpha=1, beta=2, mu=0, V=None, fit_intercept=True): r""" ...
"""A module of Bayesian linear regression models.""" import numpy as np import scipy.stats as stats from numpy_ml.utils.testing import is_number, is_symmetric_positive_definite class BayesianLinearRegressionUnknownVariance: def __init__(self, alpha=1, beta=2, mu=0, V=None, fit_intercept=True): r""" ...
12,001
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/linear_models/glm.py
129,130
48,213
fit
GeneralizedLinearModel
143,187
130,187
class GeneralizedLinearModel: def __init__(self, link, fit_intercept=True, tol=1e-5, max_iter=100): r""" A generalized linear model with maximum likelihood fit via iteratively reweighted least squares (IRLS). Notes ----- The generalized linear model (GLM) [7]_ [8]_ a...
class GeneralizedLinearModel: def __init__(self, link, fit_intercept=True, tol=1e-5, max_iter=100): r""" A generalized linear model with maximum likelihood fit via iteratively reweighted least squares (IRLS). Notes ----- The generalized linear model (GLM) [7]_ [8]_ a...
""" # noqa: E501 y = np.squeeze(y) assert y.ndim == 1 N, M = X.shape L = _GLM_LINKS[self.link] # starting values for parameters mu = np.ones_like(y) * np.mean(y) eta = L["link"](mu) theta = L["theta"](mu) # convert X to a design matrix ...
""" Find the maximum likelihood GLM coefficients via IRLS. Parameters ---------- X : :py:class:`ndarray <numpy.ndarray>` of shape `(N, M)` A dataset consisting of `N` examples, each of dimension `M`. y : :py:class:`ndarray <numpy.ndarray>` of shape `(N,)` ...
148
1,521
481
2,002
"""A module for the generalized linear model.""" import numpy as np from numpy_ml.linear_models.linear_regression import LinearRegression eps = np.finfo(float).eps _GLM_LINKS = { "logit": { "link": lambda mu: np.log((mu + eps) / (1 - mu + eps)), "inv_link": lambda eta: 1.0 / (1.0 + np.exp(-eta)),...
"""A module for the generalized linear model.""" import numpy as np from numpy_ml.linear_models.linear_regression import LinearRegression eps = np.finfo(float).eps _GLM_LINKS = { "logit": { "link": lambda mu: np.log((mu + eps) / (1 - mu + eps)), "inv_link": lambda eta: 1.0 / (1.0 + np.exp(-eta)),...
12,003
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/linear_models/logistic.py
171,172
1,174
_sigmoid
173,174
172,174
"""Logistic regression module""" import numpy as np class LogisticRegression: def __init__(self, penalty="l2", gamma=0, fit_intercept=True): r""" A simple binary logistic regression model fit via gradient descent on the penalized negative log likelihood. Notes ----- ...
"""Logistic regression module""" import numpy as np class LogisticRegression: def __init__(self, penalty="l2", gamma=0, fit_intercept=True): r""" A simple binary logistic regression model fit via gradient descent on the penalized negative log likelihood. Notes ----- ...
return 1 / (1 + np.exp(-x))
"""The logistic sigmoid function""" return 1 / (1 + np.exp(-x))
6
2,022
16
2,038
"""Logistic regression module""" import numpy as np class LogisticRegression: def __init__(self, penalty="l2", gamma=0, fit_intercept=True): r""" A simple binary logistic regression model fit via gradient descent on the penalized negative log likelihood. Notes ----- ...
"""Logistic regression module""" import numpy as np class LogisticRegression: def __init__(self, penalty="l2", gamma=0, fit_intercept=True): r""" A simple binary logistic regression model fit via gradient descent on the penalized negative log likelihood. Notes ----- ...
12,004
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/linear_models/logistic.py
121,122
5,171
_NLL
LogisticRegression
122,143
122,143
class LogisticRegression: def __init__(self, penalty="l2", gamma=0, fit_intercept=True): r""" A simple binary logistic regression model fit via gradient descent on the penalized negative log likelihood. Notes ----- In simple binary logistic regression, the entries in...
class LogisticRegression: def __init__(self, penalty="l2", gamma=0, fit_intercept=True): r""" A simple binary logistic regression model fit via gradient descent on the penalized negative log likelihood. Notes ----- In simple binary logistic regression, the entries in...
r""" Penalized negative log likelihood of the targets under the current model. .. math:: \text{NLL} = -\frac{1}{N} \left[ \left( \sum_{i=0}^N y_i \log(\hat{y}_i) + (1-y_i) \log(1-\hat{y}_i) \right) - R(\mathbf{b}, \gamma) ...
r""" Penalized negative log likelihood of the targets under the current model. .. math:: \text{NLL} = -\frac{1}{N} \left[ \left( \sum_{i=0}^N y_i \log(\hat{y}_i) + (1-y_i) \log(1-\hat{y}_i) \right) - R(\mathbf{b}, \gamma) ...
87
1,727
281
2,008
"""Logistic regression module""" import numpy as np class LogisticRegression: def __init__(self, penalty="l2", gamma=0, fit_intercept=True): r""" A simple binary logistic regression model fit via gradient descent on the penalized negative log likelihood. Notes ----- ...
"""Logistic regression module""" import numpy as np class LogisticRegression: def __init__(self, penalty="l2", gamma=0, fit_intercept=True): r""" A simple binary logistic regression model fit via gradient descent on the penalized negative log likelihood. Notes ----- ...
12,005
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/linear_models/ridge.py
86,87
6,105
predict
RidgeRegression
101,105
87,105
class RidgeRegression: def __init__(self, alpha=1, fit_intercept=True): r""" A ridge regression model with maximum likelihood fit via the normal equations. Notes ----- Ridge regression is a biased estimator for linear models which adds an additional penalty p...
class RidgeRegression: def __init__(self, alpha=1, fit_intercept=True): r""" A ridge regression model with maximum likelihood fit via the normal equations. Notes ----- Ridge regression is a biased estimator for linear models which adds an additional penalty p...
# convert X to a design matrix if we're fitting an intercept if self.fit_intercept: X = np.c_[np.ones(X.shape[0]), X] return np.dot(X, self.beta)
""" Use the trained model to generate predictions on a new collection of data points. Parameters ---------- X : :py:class:`ndarray <numpy.ndarray>` of shape `(Z, M)` A dataset consisting of `Z` new examples, each of dimension `M`. Returns ---...
21
993
66
1,059
"""Ridge regression module""" import numpy as np class RidgeRegression: def __init__(self, alpha=1, fit_intercept=True): r""" A ridge regression model with maximum likelihood fit via the normal equations. Notes ----- Ridge regression is a biased estimator for line...
"""Ridge regression module""" import numpy as np class RidgeRegression: def __init__(self, alpha=1, fit_intercept=True): r""" A ridge regression model with maximum likelihood fit via the normal equations. Notes ----- Ridge regression is a biased estimator for line...
12,006
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/neural_nets/activations/activations.py
24,26
8,30
grad
ActivationBase
27,30
26,30
class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self, z): """Apply the activation function to an input""" if z.ndim == 1: z = z.reshape(1, -1) return self.fn(z) @abstract...
class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self, z): """Apply the activation function to an input""" if z.ndim == 1: z = z.reshape(1, -1) return self.fn(z) @abstract...
raise NotImplementedError
"""Compute the gradient of the activation function wrt the input""" raise NotImplementedError
2
174
13
187
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
12,007
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/neural_nets/activations/activations.py
362,363
342,395
fn
Affine
363,372
363,372
class Affine(ActivationBase): def __init__(self, slope=1, intercept=0): """ An affine activation function. Parameters ---------- slope: float Activation slope. Default is 1. intercept: float Intercept/offset term. Default is 0. """ ...
class Affine(ActivationBase): def __init__(self, slope=1, intercept=0): """ An affine activation function. Parameters ---------- slope: float Activation slope. Default is 1. intercept: float Intercept/offset term. Default is 0. """ ...
r""" Evaluate the Affine activation on the elements of input `z`. .. math:: \text{Affine}(z_i) = \text{slope} \times z_i + \text{intercept} """ return self.slope * z + self.intercept
r""" Evaluate the Affine activation on the elements of input `z`. .. math:: \text{Affine}(z_i) = \text{slope} \times z_i + \text{intercept} """ return self.slope * z + self.intercept
27
358
89
447
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
12,008
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/neural_nets/activations/activations.py
476,477
412,491
grad2
ELU
477,491
477,491
class ELU(ActivationBase): def __init__(self, alpha=1.0): r""" An exponential linear unit (ELU). Notes ----- ELUs are intended to address the fact that ReLUs are strictly nonnegative and thus have an average activation > 0, increasing the chances of internal ...
class ELU(ActivationBase): def __init__(self, alpha=1.0): r""" An exponential linear unit (ELU). Notes ----- ELUs are intended to address the fact that ReLUs are strictly nonnegative and thus have an average activation > 0, increasing the chances of internal ...
r""" Evaluate the second derivative of the ELU activation on the elements of input `x`. .. math:: \frac{\partial^2 \text{ELU}}{\partial x_i^2} &= 0 \ \ \ \ &&\text{if } x_i > 0 \\ &= \alpha e^{x_i} \ \ \ \ &&\text{otherwise} """ ...
r""" Evaluate the second derivative of the ELU activation on the elements of input `x`. .. math:: \frac{\partial^2 \text{ELU}}{\partial x_i^2} &= 0 \ \ \ \ &&\text{if } x_i > 0 \\ &= \alpha e^{x_i} \ \ \ \ &&\text{otherwise} """ ...
59
723
168
891
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
12,009
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/neural_nets/activations/activations.py
520,521
491,532
grad2
Exponential
521,532
521,532
class Exponential(ActivationBase): def __init__(self): """An exponential (base e) activation function""" super().__init__() def __str__(self): """Return a string representation of the activation function""" return "Exponential" def fn(self, z): r""" Evaluate...
class Exponential(ActivationBase): def __init__(self): """An exponential (base e) activation function""" super().__init__() def __str__(self): """Return a string representation of the activation function""" return "Exponential" def fn(self, z): r""" Evaluate...
r""" Evaluate the second derivative of the exponential activation on the elements of input `x`. .. math:: \frac{\partial^2 \text{Exponential}}{\partial x_i^2} = e^{x_i} """ return np.exp(x)
r""" Evaluate the second derivative of the exponential activation on the elements of input `x`. .. math:: \frac{\partial^2 \text{Exponential}}{\partial x_i^2} = e^{x_i} """ return np.exp(x)
25
228
89
317
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
12,010
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/neural_nets/activations/activations.py
279,280
210,304
grad2
GELU
280,304
280,304
class GELU(ActivationBase): def __init__(self, approximate=True): r""" A Gaussian error linear unit (GELU). [*]_ Notes ----- A ReLU alternative. GELU weights inputs by their value, rather than gates inputs by their sign, as in vanilla ReLUs. References ...
class GELU(ActivationBase): def __init__(self, approximate=True): r""" A Gaussian error linear unit (GELU). [*]_ Notes ----- A ReLU alternative. GELU weights inputs by their value, rather than gates inputs by their sign, as in vanilla ReLUs. References ...
r""" Evaluate the second derivative of the GELU function on the elements of input `x`. .. math:: \frac{\partial^2 \text{GELU}}{\partial x_i^2} = \frac{1}{2\sqrt{2}} \left\[ \text{erf}'(\frac{x}{\sqrt{2}}) + \frac{1}{\s...
r""" Evaluate the second derivative of the GELU function on the elements of input `x`. .. math:: \frac{\partial^2 \text{GELU}}{\partial x_i^2} = \frac{1}{2\sqrt{2}} \left\[ \text{erf}'(\frac{x}{\sqrt{2}}) + \frac{1}{\s...
100
836
391
1,227
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
12,011
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/neural_nets/activations/activations.py
631,632
615,669
fn
HardSigmoid
632,644
632,644
class HardSigmoid(ActivationBase): def __init__(self): """ A "hard" sigmoid activation function. Notes ----- The hard sigmoid is a piecewise linear approximation of the logistic sigmoid that is computationally more efficient to compute. """ super().__...
class HardSigmoid(ActivationBase): def __init__(self): """ A "hard" sigmoid activation function. Notes ----- The hard sigmoid is a piecewise linear approximation of the logistic sigmoid that is computationally more efficient to compute. """ super().__...
r""" Evaluate the hard sigmoid activation on the elements of input `z`. .. math:: \text{HardSigmoid}(z_i) &= 0 \ \ \ \ &&\text{if }z_i < -2.5 \\ &= 0.2 z_i + 0.5 \ \ \ \ &&\text{if }-2.5 \leq z_i \leq 2.5 \\ &= 1 \ \ \ \ &&\text{if }z...
r""" Evaluate the hard sigmoid activation on the elements of input `z`. .. math:: \text{HardSigmoid}(z_i) &= 0 \ \ \ \ &&\text{if }z_i < -2.5 \\ &= 0.2 z_i + 0.5 \ \ \ \ &&\text{if }-2.5 \leq z_i \leq 2.5 \\ &= 1 \ \ \ \ &&\text{if }z...
61
374
175
549
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
12,012
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/neural_nets/activations/activations.py
169,170
140,210
fn
LeakyReLU
170,183
170,183
class LeakyReLU(ActivationBase): """ 'Leaky' version of a rectified linear unit (ReLU). Notes ----- Leaky ReLUs [*]_ are designed to address the vanishing gradient problem in ReLUs by allowing a small non-zero gradient when `x` is negative. Parameters ---------- alpha: float ...
class LeakyReLU(ActivationBase): """ 'Leaky' version of a rectified linear unit (ReLU). Notes ----- Leaky ReLUs [*]_ are designed to address the vanishing gradient problem in ReLUs by allowing a small non-zero gradient when `x` is negative. Parameters ---------- alpha: float ...
r""" Evaluate the leaky ReLU function on the elements of input `z`. .. math:: \text{LeakyReLU}(z_i) &= z_i \ \ \ \ &&\text{if } z_i > 0 \\ &= \alpha z_i \ \ \ \ &&\text{otherwise} """ _z = z.copy() _z[z < 0] = _z[z < 0] * se...
r""" Evaluate the leaky ReLU function on the elements of input `z`. .. math:: \text{LeakyReLU}(z_i) &= z_i \ \ \ \ &&\text{if } z_i > 0 \\ &= \alpha z_i \ \ \ \ &&\text{otherwise} """ _z = z.copy() _z[z < 0] = _z[z < 0] * se...
50
518
142
660
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
12,013
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/neural_nets/activations/activations.py
116,117
73,140
grad
ReLU
117,128
117,128
class ReLU(ActivationBase): """ A rectified linear activation function. Notes ----- "ReLU units can be fragile during training and can "die". For example, a large gradient flowing through a ReLU neuron could cause the weights to update in such a way that the neuron will never activate on an...
class ReLU(ActivationBase): """ A rectified linear activation function. Notes ----- "ReLU units can be fragile during training and can "die". For example, a large gradient flowing through a ReLU neuron could cause the weights to update in such a way that the neuron will never activate on an...
r""" Evaulate the first derivative of the ReLU function on the elements of input `x`. .. math:: \frac{\partial \text{ReLU}}{\partial x_i} &= 1 \ \ \ \ &&\text{if }x_i > 0 \\ &= 0 \ \ \ \ &&\text{otherwise} """ return (x > 0).astyp...
r""" Evaulate the first derivative of the ReLU function on the elements of input `x`. .. math:: \frac{\partial \text{ReLU}}{\partial x_i} &= 1 \ \ \ \ &&\text{if }x_i > 0 \\ &= 0 \ \ \ \ &&\text{otherwise} """ return (x > 0).astyp...
43
523
120
643
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
12,014
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/neural_nets/activations/activations.py
568,569
532,615
fn
SELU
569,586
569,586
class SELU(ActivationBase): r""" A scaled exponential linear unit (SELU). Notes ----- SELU units, when used in conjunction with proper weight initialization and regularization techniques, encourage neuron activations to converge to zero-mean and unit variance without explicit use of e.g., b...
class SELU(ActivationBase): r""" A scaled exponential linear unit (SELU). Notes ----- SELU units, when used in conjunction with proper weight initialization and regularization techniques, encourage neuron activations to converge to zero-mean and unit variance without explicit use of e.g., b...
r""" Evaluate the SELU activation on the elements of input `z`. .. math:: \text{SELU}(z_i) = \text{scale} \times \text{ELU}(z_i, \alpha) which is simply .. math:: \text{SELU}(z_i) &= \text{scale} \times z_i \ \ \ \ &&\text{if }z_i > ...
r""" Evaluate the SELU activation on the elements of input `z`. .. math:: \text{SELU}(z_i) = \text{scale} \times \text{ELU}(z_i, \alpha) which is simply .. math:: \text{SELU}(z_i) &= \text{scale} \times z_i \ \ \ \ &&\text{if }z_i > ...
55
788
194
982
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
12,015
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/neural_nets/activations/activations.py
39,40
30,73
fn
Sigmoid
40,49
40,49
class Sigmoid(ActivationBase): def __init__(self): """A logistic sigmoid activation function.""" super().__init__() def __str__(self): """Return a string representation of the activation function""" return "Sigmoid" def fn(self, z): FILL_FUNC_BODY def grad(self, x): ...
class Sigmoid(ActivationBase): def __init__(self): """A logistic sigmoid activation function.""" super().__init__() def __str__(self): """Return a string representation of the activation function""" return "Sigmoid" def fn(self, z): FILL_FUNC_BODY def grad(self, x): ...
r""" Evaluate the logistic sigmoid, :math:`\sigma`, on the elements of input `z`. .. math:: \sigma(x_i) = \frac{1}{1 + e^{-x_i}} """ return 1 / (1 + np.exp(-z))
r""" Evaluate the logistic sigmoid, :math:`\sigma`, on the elements of input `z`. .. math:: \sigma(x_i) = \frac{1}{1 + e^{-x_i}} """ return 1 / (1 + np.exp(-z))
26
323
92
415
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
12,016
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/neural_nets/activations/activations.py
710,711
669,722
grad2
SoftPlus
711,722
711,722
class SoftPlus(ActivationBase): def __init__(self): """ A softplus activation function. Notes ----- In contrast to :class:`ReLU`, the softplus activation is differentiable everywhere (including 0). It is, however, less computationally efficient to compute. ...
class SoftPlus(ActivationBase): def __init__(self): """ A softplus activation function. Notes ----- In contrast to :class:`ReLU`, the softplus activation is differentiable everywhere (including 0). It is, however, less computationally efficient to compute. ...
r""" Evaluate the second derivative of the softplus activation on the elements of input `x`. .. math:: \frac{\partial^2 \text{SoftPlus}}{\partial x_i^2} = \frac{e^{x_i}}{(1 + e^{x_i})^2} """ exp_x = np.exp(x) return exp_x / ((exp_x + ...
r""" Evaluate the second derivative of the softplus activation on the elements of input `x`. .. math:: \frac{\partial^2 \text{SoftPlus}}{\partial x_i^2} = \frac{e^{x_i}}{(1 + e^{x_i})^2} """ exp_x = np.exp(x) return exp_x / ((exp_x + ...
36
351
126
477
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
12,017
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/neural_nets/activations/activations.py
328,329
304,342
grad2
Tanh
329,342
329,342
class Tanh(ActivationBase): def __init__(self): """A hyperbolic tangent activation function.""" super().__init__() def __str__(self): """Return a string representation of the activation function""" return "Tanh" def fn(self, z): """Compute the tanh function on the e...
class Tanh(ActivationBase): def __init__(self): """A hyperbolic tangent activation function.""" super().__init__() def __str__(self): """Return a string representation of the activation function""" return "Tanh" def fn(self, z): """Compute the tanh function on the e...
r""" Evaluate the second derivative of the tanh function on the elements of input `x`. .. math:: \frac{\partial^2 \tanh}{\partial x_i^2} = -2 \tanh(x) \left(\frac{\partial \tanh}{\partial x_i}\right) """ tanh_x = np.tanh(x) return -2 ...
r""" Evaluate the second derivative of the tanh function on the elements of input `x`. .. math:: \frac{\partial^2 \tanh}{\partial x_i^2} = -2 \tanh(x) \left(\frac{\partial \tanh}{\partial x_i}\right) """ tanh_x = np.tanh(x) return -2 ...
40
215
136
351
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
"""A collection of activation function objects for building neural networks""" from math import erf from abc import ABC, abstractmethod import numpy as np class ActivationBase(ABC): def __init__(self, **kwargs): """Initialize the ActivationBase object""" super().__init__() def __call__(self,...
12,018
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/neural_nets/losses/losses.py
169,171
110,225
grad
CrossEntropy
212,225
171,225
class CrossEntropy(ObjectiveBase): def __init__(self): """ A cross-entropy loss. Notes ----- For a one-hot target **y** and predicted class probabilities :math:`\hat{\mathbf{y}}`, the cross entropy is .. math:: \mathcal{L}(\mathbf{y}, \hat{\m...
class CrossEntropy(ObjectiveBase): def __init__(self): """ A cross-entropy loss. Notes ----- For a one-hot target **y** and predicted class probabilities :math:`\hat{\mathbf{y}}`, the cross entropy is .. math:: \mathcal{L}(\mathbf{y}, \hat{\m...
is_binary(y) is_stochastic(y_pred) # derivative of xe wrt z is y_pred - y_true, hence we can just # subtract 1 from the probability of the correct class labels grad = y_pred - y # [optional] scale the gradients by the number of examples in the batch # n, m = y.s...
""" Compute the gradient of the cross entropy loss with regard to the softmax input, `z`. Notes ----- The gradient for this method goes through both the cross-entropy loss AND the softmax non-linearity to return :math:`\\frac{\partial \mathcal{L}}{\partia...
56
963
122
1,085
from abc import ABC, abstractmethod import numpy as np from ...utils.testing import is_binary, is_stochastic from ..initializers import ( WeightInitializer, ActivationInitializer, OptimizerInitializer, ) class ObjectiveBase(ABC): def __init__(self): super().__init__() @abstractmethod ...
from abc import ABC, abstractmethod import numpy as np from ...utils.testing import is_binary, is_stochastic from ..initializers import ( WeightInitializer, ActivationInitializer, OptimizerInitializer, ) class ObjectiveBase(ABC): def __init__(self): super().__init__() @abstractmethod ...
12,020
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/neural_nets/losses/losses.py
67,69
26,110
grad
SquaredError
107,110
69,110
class SquaredError(ObjectiveBase): def __init__(self): """ A squared-error / `L2` loss. Notes ----- For real-valued target **y** and predictions :math:`\hat{\mathbf{y}}`, the squared error is .. math:: \mathcal{L}(\mathbf{y}, \hat{\mathbf{y}}...
class SquaredError(ObjectiveBase): def __init__(self): """ A squared-error / `L2` loss. Notes ----- For real-valued target **y** and predictions :math:`\hat{\mathbf{y}}`, the squared error is .. math:: \mathcal{L}(\mathbf{y}, \hat{\mathbf{y}}...
return (y_pred - y) * act_fn.grad(z)
""" Gradient of the squared error loss with respect to the pre-nonlinearity input, `z`. Notes ----- The current method computes the gradient :math:`\\frac{\partial \mathcal{L}}{\partial \mathbf{z}}`, where .. math:: \mathcal{L}(\mathbf{z}) ...
6
805
24
829
from abc import ABC, abstractmethod import numpy as np from ...utils.testing import is_binary, is_stochastic from ..initializers import ( WeightInitializer, ActivationInitializer, OptimizerInitializer, ) class ObjectiveBase(ABC): def __init__(self): super().__init__() @abstractmethod ...
from abc import ABC, abstractmethod import numpy as np from ...utils.testing import is_binary, is_stochastic from ..initializers import ( WeightInitializer, ActivationInitializer, OptimizerInitializer, ) class ObjectiveBase(ABC): def __init__(self): super().__init__() @abstractmethod ...
12,021
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/neural_nets/losses/losses.py
260,262
225,331
loss
VAELoss
282,295
262,295
class VAELoss(ObjectiveBase): def __init__(self): """ The variational lower bound for a variational autoencoder with Bernoulli units. Notes ----- The VLB to the sum of the binary cross entropy between the true input and the predicted output (the "reconstructi...
class VAELoss(ObjectiveBase): def __init__(self): """ The variational lower bound for a variational autoencoder with Bernoulli units. Notes ----- The VLB to the sum of the binary cross entropy between the true input and the predicted output (the "reconstructi...
# prevent nan on log(0) eps = np.finfo(float).eps y_pred = np.clip(y_pred, eps, 1 - eps) # reconstruction loss: binary cross-entropy rec_loss = -np.sum(y * np.log(y_pred) + (1 - y) * np.log(1 - y_pred), axis=1) # KL divergence between the variational distribution q and ...
""" Variational lower bound for a Bernoulli VAE. Parameters ---------- y : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, N)` The original images. y_pred : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, N)` The VAE reconstruction of th...
71
1,231
205
1,436
from abc import ABC, abstractmethod import numpy as np from ...utils.testing import is_binary, is_stochastic from ..initializers import ( WeightInitializer, ActivationInitializer, OptimizerInitializer, ) class ObjectiveBase(ABC): def __init__(self): super().__init__() @abstractmethod ...
from abc import ABC, abstractmethod import numpy as np from ...utils.testing import is_binary, is_stochastic from ..initializers import ( WeightInitializer, ActivationInitializer, OptimizerInitializer, ) class ObjectiveBase(ABC): def __init__(self): super().__init__() @abstractmethod ...
12,025
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/neural_nets/optimizers/optimizers.py
215,216
156,262
update
AdaGrad
243,262
216,262
class AdaGrad(OptimizerBase): def __init__(self, lr=0.01, eps=1e-7, clip_norm=None, lr_scheduler=None, **kwargs): """ An AdaGrad optimizer. Notes ----- Weights that receive large gradients will have their effective learning rate reduced, while weights that receive sm...
class AdaGrad(OptimizerBase): def __init__(self, lr=0.01, eps=1e-7, clip_norm=None, lr_scheduler=None, **kwargs): """ An AdaGrad optimizer. Notes ----- Weights that receive large gradients will have their effective learning rate reduced, while weights that receive sm...
C = self.cache H = self.hyperparameters eps, clip_norm = H["eps"], H["clip_norm"] lr = self.lr_scheduler(self.cur_step, cur_loss) if param_name not in C: C[param_name] = np.zeros_like(param_grad) # scale gradient to avoid explosion t = np.inf if clip...
""" Compute the AdaGrad update for a given parameter. Notes ----- Adjusts the learning rate of each weight based on the magnitudes of its gradients (big gradient -> small lr, small gradient -> big lr). Parameters ---------- param : :py:class:`nda...
70
984
220
1,204
from copy import deepcopy from abc import ABC, abstractmethod import numpy as np from numpy.linalg import norm class OptimizerBase(ABC): def __init__(self, lr, scheduler=None): """ An abstract base class for all Optimizer objects. This should never be used directly. """ f...
from copy import deepcopy from abc import ABC, abstractmethod import numpy as np from numpy.linalg import norm class OptimizerBase(ABC): def __init__(self, lr, scheduler=None): """ An abstract base class for all Optimizer objects. This should never be used directly. """ f...
12,026
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/neural_nets/optimizers/optimizers.py
427,428
364,483
update
Adam
450,483
428,483
class Adam(OptimizerBase): def __init__( self, lr=0.001, decay1=0.9, decay2=0.999, eps=1e-7, clip_norm=None, lr_scheduler=None, **kwargs ): """ Adam (adaptive moment estimation) optimization algorithm. Notes ----- ...
class Adam(OptimizerBase): def __init__( self, lr=0.001, decay1=0.9, decay2=0.999, eps=1e-7, clip_norm=None, lr_scheduler=None, **kwargs ): """ Adam (adaptive moment estimation) optimization algorithm. Notes ----- ...
C = self.cache H = self.hyperparameters d1, d2 = H["decay1"], H["decay2"] eps, clip_norm = H["eps"], H["clip_norm"] lr = self.lr_scheduler(self.cur_step, cur_loss) if param_name not in C: C[param_name] = { "t": 0, "mean": np.ze...
""" Compute the Adam update for a given parameter. Parameters ---------- param : :py:class:`ndarray <numpy.ndarray>` of shape (n, m) The value of the parameter to be updated. param_grad : :py:class:`ndarray <numpy.ndarray>` of shape (n, m) The gra...
144
979
446
1,425
from copy import deepcopy from abc import ABC, abstractmethod import numpy as np from numpy.linalg import norm class OptimizerBase(ABC): def __init__(self, lr, scheduler=None): """ An abstract base class for all Optimizer objects. This should never be used directly. """ f...
from copy import deepcopy from abc import ABC, abstractmethod import numpy as np from numpy.linalg import norm class OptimizerBase(ABC): def __init__(self, lr, scheduler=None): """ An abstract base class for all Optimizer objects. This should never be used directly. """ f...
12,027
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/neural_nets/optimizers/optimizers.py
37,38
8,58
set_params
OptimizerBase
39,53
38,53
class OptimizerBase(ABC): def __init__(self, lr, scheduler=None): """ An abstract base class for all Optimizer objects. This should never be used directly. """ from ..initializers import SchedulerInitializer self.cache = {} self.cur_step = 0 self.hyp...
class OptimizerBase(ABC): def __init__(self, lr, scheduler=None): """ An abstract base class for all Optimizer objects. This should never be used directly. """ from ..initializers import SchedulerInitializer self.cache = {} self.cur_step = 0 self.hyp...
from ..initializers import SchedulerInitializer if hparam_dict is not None: for k, v in hparam_dict.items(): if k in self.hyperparameters: self.hyperparameters[k] = v if k == "lr_scheduler": self.lr_scheduler = ...
"""Set the parameters of the optimizer object from a dictionary""" from ..initializers import SchedulerInitializer if hparam_dict is not None: for k, v in hparam_dict.items(): if k in self.hyperparameters: self.hyperparameters[k] = v ...
46
338
153
491
from copy import deepcopy from abc import ABC, abstractmethod import numpy as np from numpy.linalg import norm class OptimizerBase(ABC): def __init__(self, lr, scheduler=None): """ An abstract base class for all Optimizer objects. This should never be used directly. """ f...
from copy import deepcopy from abc import ABC, abstractmethod import numpy as np from numpy.linalg import norm class OptimizerBase(ABC): def __init__(self, lr, scheduler=None): """ An abstract base class for all Optimizer objects. This should never be used directly. """ f...
12,028
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/neural_nets/optimizers/optimizers.py
322,323
262,364
update
RMSProp
345,364
323,364
class RMSProp(OptimizerBase): def __init__( self, lr=0.001, decay=0.9, eps=1e-7, clip_norm=None, lr_scheduler=None, **kwargs ): """ RMSProp optimizer. Notes ----- RMSProp was proposed as a refinement of :class:`AdaGrad` to reduce its aggressive, monotonic...
class RMSProp(OptimizerBase): def __init__( self, lr=0.001, decay=0.9, eps=1e-7, clip_norm=None, lr_scheduler=None, **kwargs ): """ RMSProp optimizer. Notes ----- RMSProp was proposed as a refinement of :class:`AdaGrad` to reduce its aggressive, monotonic...
C = self.cache H = self.hyperparameters eps, decay, clip_norm = H["eps"], H["decay"], H["clip_norm"] lr = self.lr_scheduler(self.cur_step, cur_loss) if param_name not in C: C[param_name] = np.zeros_like(param_grad) # scale gradient to avoid explosion ...
""" Compute the RMSProp update for a given parameter. Parameters ---------- param : :py:class:`ndarray <numpy.ndarray>` of shape (n, m) The value of the parameter to be updated param_grad : :py:class:`ndarray <numpy.ndarray>` of shape (n, m) The g...
80
990
242
1,232
from copy import deepcopy from abc import ABC, abstractmethod import numpy as np from numpy.linalg import norm class OptimizerBase(ABC): def __init__(self, lr, scheduler=None): """ An abstract base class for all Optimizer objects. This should never be used directly. """ f...
from copy import deepcopy from abc import ABC, abstractmethod import numpy as np from numpy.linalg import norm class OptimizerBase(ABC): def __init__(self, lr, scheduler=None): """ An abstract base class for all Optimizer objects. This should never be used directly. """ f...
12,029
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/neural_nets/optimizers/optimizers.py
110,111
58,156
update
SGD
133,156
111,156
class SGD(OptimizerBase): def __init__( self, lr=0.01, momentum=0.0, clip_norm=None, lr_scheduler=None, **kwargs ): """ A stochastic gradient descent optimizer. Notes ----- For model parameters :math:`\\theta`, averaged parameter gradients :math:`\\nabla_...
class SGD(OptimizerBase): def __init__( self, lr=0.01, momentum=0.0, clip_norm=None, lr_scheduler=None, **kwargs ): """ A stochastic gradient descent optimizer. Notes ----- For model parameters :math:`\\theta`, averaged parameter gradients :math:`\\nabla_...
C = self.cache H = self.hyperparameters momentum, clip_norm = H["momentum"], H["clip_norm"] lr = self.lr_scheduler(self.cur_step, cur_loss) if param_name not in C: C[param_name] = np.zeros_like(param_grad) # scale gradient to avoid explosion t = np.i...
""" Compute the SGD update for a given parameter Parameters ---------- param : :py:class:`ndarray <numpy.ndarray>` of shape (n, m) The value of the parameter to be updated. param_grad : :py:class:`ndarray <numpy.ndarray>` of shape (n, m) The gradi...
72
892
230
1,122
from copy import deepcopy from abc import ABC, abstractmethod import numpy as np from numpy.linalg import norm class OptimizerBase(ABC): def __init__(self, lr, scheduler=None): """ An abstract base class for all Optimizer objects. This should never be used directly. """ f...
from copy import deepcopy from abc import ABC, abstractmethod import numpy as np from numpy.linalg import norm class OptimizerBase(ABC): def __init__(self, lr, scheduler=None): """ An abstract base class for all Optimizer objects. This should never be used directly. """ f...
12,030
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/ngram/ngram.py
402,403
364,459
log_prob
AdditiveNGram
403,446
403,446
class AdditiveNGram(NGramBase): def __init__( self, N, K=1, unk=True, filter_stopwords=True, filter_punctuation=True, ): """ An N-Gram model with smoothed probabilities calculated via additive / Lidstone smoothing. Notes ----- The resulting estimates corr...
class AdditiveNGram(NGramBase): def __init__( self, N, K=1, unk=True, filter_stopwords=True, filter_punctuation=True, ): """ An N-Gram model with smoothed probabilities calculated via additive / Lidstone smoothing. Notes ----- The resulting estimates corr...
r""" Compute the smoothed log probability of a sequence of words under the `N`-gram language model with additive smoothing. Notes ----- For a bigram, additive smoothing amounts to: .. math:: P(w_i \mid w_{i-1}) = \frac{A + K}{B + KV} where ...
r""" Compute the smoothed log probability of a sequence of words under the `N`-gram language model with additive smoothing. Notes ----- For a bigram, additive smoothing amounts to: .. math:: P(w_i \mid w_{i-1}) = \frac{A + K}{B + KV} where ...
157
603
412
1,015
"""A module for different N-gram smoothing models""" import textwrap from abc import ABC, abstractmethod from collections import Counter import numpy as np from numpy_ml.linear_models import LinearRegression from numpy_ml.preprocessing.nlp import tokenize_words, ngrams, strip_punctuation class NGramBase(ABC): d...
"""A module for different N-gram smoothing models""" import textwrap from abc import ABC, abstractmethod from collections import Counter import numpy as np from numpy_ml.linear_models import LinearRegression from numpy_ml.preprocessing.nlp import tokenize_words, ngrams, strip_punctuation class NGramBase(ABC): d...
12,032
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/ngram/ngram.py
356,357
313,364
_log_ngram_prob
MLENGram
358,364
357,364
class MLENGram(NGramBase): def __init__(self, N, unk=True, filter_stopwords=True, filter_punctuation=True): """ A simple, unsmoothed N-gram model. Parameters ---------- N : int The maximum length (in words) of the context-window to use in the langauge...
class MLENGram(NGramBase): def __init__(self, N, unk=True, filter_stopwords=True, filter_punctuation=True): """ A simple, unsmoothed N-gram model. Parameters ---------- N : int The maximum length (in words) of the context-window to use in the langauge...
N = len(ngram) num = self.counts[N][ngram] den = self.counts[N - 1][ngram[:-1]] if N > 1 else self.n_words[1] return np.log(num) - np.log(den) if (den > 0 and num > 0) else -np.inf
"""Return the unsmoothed log probability of the ngram""" N = len(ngram) num = self.counts[N][ngram] den = self.counts[N - 1][ngram[:-1]] if N > 1 else self.n_words[1] return np.log(num) - np.log(den) if (den > 0 and num > 0) else -np.inf
31
429
95
524
"""A module for different N-gram smoothing models""" import textwrap from abc import ABC, abstractmethod from collections import Counter import numpy as np from numpy_ml.linear_models import LinearRegression from numpy_ml.preprocessing.nlp import tokenize_words, ngrams, strip_punctuation class NGramBase(ABC): d...
"""A module for different N-gram smoothing models""" import textwrap from abc import ABC, abstractmethod from collections import Counter import numpy as np from numpy_ml.linear_models import LinearRegression from numpy_ml.preprocessing.nlp import tokenize_words, ngrams, strip_punctuation class NGramBase(ABC): d...
12,034
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/nonparametric/kernel_regression.py
53,54
4,71
predict
KernelRegression
67,71
54,71
class KernelRegression: def __init__(self, kernel=None): """ A Nadaraya-Watson kernel regression model. Notes ----- The Nadaraya-Watson regression model is .. math:: f(x) = \sum_i w_i(x) y_i where the sample weighting functions, :math:`w_i`, ar...
class KernelRegression: def __init__(self, kernel=None): """ A Nadaraya-Watson kernel regression model. Notes ----- The Nadaraya-Watson regression model is .. math:: f(x) = \sum_i w_i(x) y_i where the sample weighting functions, :math:`w_i`, ar...
K = self.kernel P = self.parameters sim = K(P["X"], X) return (sim * P["y"][:, None]).sum(axis=0) / sim.sum(axis=0)
""" Generate predictions for the targets associated with the rows in `X`. Parameters ---------- X : :py:class:`ndarray <numpy.ndarray>` of shape `(N', M')` An array of `N'` examples to generate predictions on Returns ------- y : :py:class:`nd...
17
641
61
702
from ..utils.kernels import KernelInitializer class KernelRegression: def __init__(self, kernel=None): """ A Nadaraya-Watson kernel regression model. Notes ----- The Nadaraya-Watson regression model is .. math:: f(x) = \sum_i w_i(x) y_i where...
from ..utils.kernels import KernelInitializer class KernelRegression: def __init__(self, kernel=None): """ A Nadaraya-Watson kernel regression model. Notes ----- The Nadaraya-Watson regression model is .. math:: f(x) = \sum_i w_i(x) y_i where...
12,035
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/nonparametric/knn.py
62,63
9,102
predict
KNN
63,102
63,102
class KNN: def __init__( self, k=5, leaf_size=40, classifier=True, metric=None, weights="uniform", ): """ A `k`-nearest neighbors (kNN) model relying on a ball tree for efficient computation. Parameters ---------- k : int The number of neighbo...
class KNN: def __init__( self, k=5, leaf_size=40, classifier=True, metric=None, weights="uniform", ): """ A `k`-nearest neighbors (kNN) model relying on a ball tree for efficient computation. Parameters ---------- k : int The number of neighbo...
r""" Generate predictions for the targets associated with the rows in `X`. Parameters ---------- X : numpy array of shape `(N', M')` An array of `N'` examples to generate predictions on. Returns ------- y : numpy array of shape `(N', *)` ...
r""" Generate predictions for the targets associated with the rows in `X`. Parameters ---------- X : numpy array of shape `(N', M')` An array of `N'` examples to generate predictions on. Returns ------- y : numpy array of shape `(N', *)` ...
171
568
460
1,028
"""A k-Nearest Neighbors (KNN) model for both classiciation and regression.""" from collections import Counter import numpy as np from ..utils.data_structures import BallTree class KNN: def __init__( self, k=5, leaf_size=40, classifier=True, metric=None, weights="uniform", ): """ A `...
"""A k-Nearest Neighbors (KNN) model for both classiciation and regression.""" from collections import Counter import numpy as np from ..utils.data_structures import BallTree class KNN: def __init__( self, k=5, leaf_size=40, classifier=True, metric=None, weights="uniform", ): """ A `...
12,036
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/plots/bandit_plots.py
151,152
1,172
plot_comparison
156,172
152,172
"""Miscellaneous plots for multi-arm bandit validation""" from collections import namedtuple import numpy as np from numpy_ml.bandits import ( MultinomialBandit, BernoulliBandit, ShortestPathBandit, ContextualLinearBandit, ) from numpy_ml.bandits.trainer import BanditTrainer from numpy_ml.bandits.pol...
"""Miscellaneous plots for multi-arm bandit validation""" from collections import namedtuple import numpy as np from numpy_ml.bandits import ( MultinomialBandit, BernoulliBandit, ShortestPathBandit, ContextualLinearBandit, ) from numpy_ml.bandits.trainer import BanditTrainer from numpy_ml.bandits.pol...
np.random.seed(1234) ep_length = 1 K = 10 n_duplicates = 5 n_episodes = 5000 cmab = random_bernoulli_mab(n_arms=K) policy1 = EpsilonGreedy(epsilon=0.05, ev_prior=0.5) policy2 = UCB1(C=1, ev_prior=0.5) policy3 = ThompsonSamplingBetaBinomial(alpha=1, beta=1) policies = [policy1, ...
""" Use the BanditTrainer to compare several policies on the same bandit problem """ np.random.seed(1234) ep_length = 1 K = 10 n_duplicates = 5 n_episodes = 5000 cmab = random_bernoulli_mab(n_arms=K) policy1 = EpsilonGreedy(epsilon=0.05, ev_prior=0.5) policy2 = UCB1(C=1...
40
1,780
207
1,987
"""Miscellaneous plots for multi-arm bandit validation""" from collections import namedtuple import numpy as np from numpy_ml.bandits import ( MultinomialBandit, BernoulliBandit, ShortestPathBandit, ContextualLinearBandit, ) from numpy_ml.bandits.trainer import BanditTrainer from numpy_ml.bandits.pol...
"""Miscellaneous plots for multi-arm bandit validation""" from collections import namedtuple import numpy as np from numpy_ml.bandits import ( MultinomialBandit, BernoulliBandit, ShortestPathBandit, ContextualLinearBandit, ) from numpy_ml.bandits.trainer import BanditTrainer from numpy_ml.bandits.pol...
12,039
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/preprocessing/general.py
368,369
275,389
_encode_sparse
FeatureHasher
369,389
369,389
class FeatureHasher: def __init__(self, n_dim=256, sparse=True): """ Convert a collection of features to a fixed-dimensional matrix using the hashing trick. Notes ----- Uses the md5 hash. Parameters ---------- n_dim : int The dime...
class FeatureHasher: def __init__(self, n_dim=256, sparse=True): """ Convert a collection of features to a fixed-dimensional matrix using the hashing trick. Notes ----- Uses the md5 hash. Parameters ---------- n_dim : int The dime...
N = len(examples) idxs, data = [], [] for row, feat_dict in enumerate(examples): for f_id, val in feat_dict.items(): if isinstance(f_id, str): f_id = f_id.encode("utf-8") # use json module to convert the feature id into a unique ...
N = len(examples) idxs, data = [], [] for row, feat_dict in enumerate(examples): for f_id, val in feat_dict.items(): if isinstance(f_id, str): f_id = f_id.encode("utf-8") # use json module to convert the feature id into a unique ...
77
1,009
264
1,273
import json import hashlib import warnings import numpy as np try: from scipy.sparse import csr_matrix _SCIPY = True except ImportError: warnings.warn("Scipy not installed. FeatureHasher can only create dense matrices") _SCIPY = False def minibatch(X, batchsize=256, shuffle=True): """ Compu...
import json import hashlib import warnings import numpy as np try: from scipy.sparse import csr_matrix _SCIPY = True except ImportError: warnings.warn("Scipy not installed. FeatureHasher can only create dense matrices") _SCIPY = False def minibatch(X, batchsize=256, shuffle=True): """ Compu...
12,040
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/preprocessing/general.py
72,73
54,141
fit
OneHotEncoder
81,86
73,86
class OneHotEncoder: def __init__(self): """ Convert between category labels and their one-hot vector representations. Parameters ---------- categories : list of length `C` List of the unique category labels for the items to encode. """ se...
class OneHotEncoder: def __init__(self): """ Convert between category labels and their one-hot vector representations. Parameters ---------- categories : list of length `C` List of the unique category labels for the items to encode. """ se...
self.parameters["categories"] = categories self.cat2idx = {c: i for i, c in enumerate(categories)} self.idx2cat = {i: c for i, c in enumerate(categories)} self._is_fit = True
""" Create mappings between columns and category labels. Parameters ---------- categories : list of length `C` List of the unique category labels for the items to encode. """ self.parameters["categories"] = categories self.cat2idx = {c: i for ...
24
741
72
813
import json import hashlib import warnings import numpy as np try: from scipy.sparse import csr_matrix _SCIPY = True except ImportError: warnings.warn("Scipy not installed. FeatureHasher can only create dense matrices") _SCIPY = False def minibatch(X, batchsize=256, shuffle=True): """ Compu...
import json import hashlib import warnings import numpy as np try: from scipy.sparse import csr_matrix _SCIPY = True except ImportError: warnings.warn("Scipy not installed. FeatureHasher can only create dense matrices") _SCIPY = False def minibatch(X, batchsize=256, shuffle=True): """ Compu...
12,041
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/preprocessing/general.py
187,188
141,275
fit
Standardizer
197,216
188,216
class Standardizer: def __init__(self, with_mean=True, with_std=True): """ Feature-wise standardization for vector inputs. Notes ----- Due to the sensitivity of empirical mean and standard deviation calculations to extreme values, `Standardizer` cannot guarantee ...
class Standardizer: def __init__(self, with_mean=True, with_std=True): """ Feature-wise standardization for vector inputs. Notes ----- Due to the sensitivity of empirical mean and standard deviation calculations to extreme values, `Standardizer` cannot guarantee ...
if not isinstance(X, np.ndarray): X = np.array(X) if X.shape[0] < 2: raise ValueError("`X` must contain at least 2 samples") std = np.ones(X.shape[1]) mean = np.zeros(X.shape[1]) if self.with_mean: mean = np.mean(X, axis=0) if self....
""" Store the feature-wise mean and standard deviation across the samples in `X` for future scaling. Parameters ---------- X : :py:class:`ndarray <numpy.ndarray>` of shape `(N, C)` An array of N samples, each with dimensionality `C` """ if not...
47
1,041
182
1,223
import json import hashlib import warnings import numpy as np try: from scipy.sparse import csr_matrix _SCIPY = True except ImportError: warnings.warn("Scipy not installed. FeatureHasher can only create dense matrices") _SCIPY = False def minibatch(X, batchsize=256, shuffle=True): """ Compu...
import json import hashlib import warnings import numpy as np try: from scipy.sparse import csr_matrix _SCIPY = True except ImportError: warnings.warn("Scipy not installed. FeatureHasher can only create dense matrices") _SCIPY = False def minibatch(X, batchsize=256, shuffle=True): """ Compu...
12,044
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/preprocessing/nlp.py
521,522
431,573
_build_tree
HuffmanEncoder
523,548
522,548
class HuffmanEncoder(object): def fit(self, text): """ Build a Huffman tree for the tokens in `text` and compute each token's binary encoding. Notes ----- In a Huffman code, tokens that occur more frequently are (generally) represented using fewer bits. Huffm...
class HuffmanEncoder(object): def fit(self, text): """ Build a Huffman tree for the tokens in `text` and compute each token's binary encoding. Notes ----- In a Huffman code, tokens that occur more frequently are (generally) represented using fewer bits. Huffm...
PQ = [] if isinstance(text, Vocabulary): counts = text.counts else: counts = self._counter(text) for (k, c) in counts.items(): PQ.append(Node(k, c)) # create a priority queue with priority = item frequency heapq.heapify(PQ) ...
"""Construct Huffman Tree""" PQ = [] if isinstance(text, Vocabulary): counts = text.counts else: counts = self._counter(text) for (k, c) in counts.items(): PQ.append(Node(k, c)) # create a priority queue with priority = item frequenc...
69
1,058
241
1,299
"""Common preprocessing utilities for working with text data""" import re import heapq import os.path as op from collections import Counter, OrderedDict, defaultdict import numpy as np # This list of English stop words is taken from the "Glasgow Information # Retrieval Group". The original list can be found at # htt...
"""Common preprocessing utilities for working with text data""" import re import heapq import os.path as op from collections import Counter, OrderedDict, defaultdict import numpy as np # This list of English stop words is taken from the "Glasgow Information # Retrieval Group". The original list can be found at # htt...
12,047
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/rl_models/tiles/tiles3.py
90,91
1,122
tiles
92,106
91,106
""" Tile Coding Software version 3.0beta by Rich Sutton based on a program created by Steph Schaeffer and others External documentation and recommendations on the use of this code is available in the reinforcement learning textbook by Sutton and Barto, and on the web. These need to be understood before this code is. T...
""" Tile Coding Software version 3.0beta by Rich Sutton based on a program created by Steph Schaeffer and others External documentation and recommendations on the use of this code is available in the reinforcement learning textbook by Sutton and Barto, and on the web. These need to be understood before this code is. T...
qfloats = [floor(f * numtilings) for f in floats] Tiles = [] for tiling in range(numtilings): tilingX2 = tiling * 2 coords = [tiling] b = tiling for q in qfloats: coords.append((q + b) // numtilings) b += tilingX2 coords.extend(ints) Ti...
"""returns num-tilings tile indices corresponding to the floats and ints""" qfloats = [floor(f * numtilings) for f in floats] Tiles = [] for tiling in range(numtilings): tilingX2 = tiling * 2 coords = [tiling] b = tiling for q in qfloats: coords.append((q + b)...
45
1,056
150
1,206
""" Tile Coding Software version 3.0beta by Rich Sutton based on a program created by Steph Schaeffer and others External documentation and recommendations on the use of this code is available in the reinforcement learning textbook by Sutton and Barto, and on the web. These need to be understood before this code is. T...
""" Tile Coding Software version 3.0beta by Rich Sutton based on a program created by Steph Schaeffer and others External documentation and recommendations on the use of this code is available in the reinforcement learning textbook by Sutton and Barto, and on the web. These need to be understood before this code is. T...
12,048
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/rl_models/tiles/tiles3.py
63,64
36,81
getindex
IHT
64,81
64,81
class IHT: "Structure to handle collisions" def __init__(self, sizeval): self.size = sizeval self.overfullCount = 0 self.dictionary = {} def __str__(self): "Prepares a string for printing whenever this object is printed" return ( "Collision table:" ...
class IHT: "Structure to handle collisions" def __init__(self, sizeval): self.size = sizeval self.overfullCount = 0 self.dictionary = {} def __str__(self): "Prepares a string for printing whenever this object is printed" return ( "Collision table:" ...
d = self.dictionary if obj in d: return d[obj] elif readonly: return None size = self.size count = self.count() if count >= size: if self.overfullCount == 0: print("IHT full, starting to allow collisions") se...
d = self.dictionary if obj in d: return d[obj] elif readonly: return None size = self.size count = self.count() if count >= size: if self.overfullCount == 0: print("IHT full, starting to allow collisions") se...
46
214
133
347
""" Tile Coding Software version 3.0beta by Rich Sutton based on a program created by Steph Schaeffer and others External documentation and recommendations on the use of this code is available in the reinforcement learning textbook by Sutton and Barto, and on the web. These need to be understood before this code is. T...
""" Tile Coding Software version 3.0beta by Rich Sutton based on a program created by Steph Schaeffer and others External documentation and recommendations on the use of this code is available in the reinforcement learning textbook by Sutton and Barto, and on the web. These need to be understood before this code is. T...
12,049
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/trees/losses.py
12,13
8,18
predict
ClassProbEstimator
13,18
13,18
class ClassProbEstimator: def fit(self, X, y): self.class_prob = y.sum() / len(y) def predict(self, X): FILL_FUNC_BODY
class ClassProbEstimator: def fit(self, X, y): self.class_prob = y.sum() / len(y) def predict(self, X): FILL_FUNC_BODY
pred = np.empty(X.shape[0], dtype=np.float64) pred.fill(self.class_prob) return pred
pred = np.empty(X.shape[0], dtype=np.float64) pred.fill(self.class_prob) return pred
7
56
46
102
import numpy as np ####################################################################### # Base Estimators # ####################################################################### class ClassProbEstimator: def fit(self, X, y): self.class_prob = y.sum...
import numpy as np ####################################################################### # Base Estimators # ####################################################################### class ClassProbEstimator: def fit(self, X, y): self.class_prob = y.sum...
12,050
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/trees/losses.py
64,65
52,66
line_search
CrossEntropyLoss
65,66
65,66
class CrossEntropyLoss: def __call__(self, y, y_pred): eps = np.finfo(float).eps return -np.sum(y * np.log(y_pred + eps)) def base_estimator(self): return ClassProbEstimator() def grad(self, y, y_pred): eps = np.finfo(float).eps return -y * 1 / (y_pred + eps) d...
class CrossEntropyLoss: def __call__(self, y, y_pred): eps = np.finfo(float).eps return -np.sum(y * np.log(y_pred + eps)) def base_estimator(self): return ClassProbEstimator() def grad(self, y, y_pred): eps = np.finfo(float).eps return -y * 1 / (y_pred + eps) d...
raise NotImplementedError
raise NotImplementedError
2
150
9
159
import numpy as np ####################################################################### # Base Estimators # ####################################################################### class ClassProbEstimator: def fit(self, X, y): self.class_prob = y.sum...
import numpy as np ####################################################################### # Base Estimators # ####################################################################### class ClassProbEstimator: def fit(self, X, y): self.class_prob = y.sum...
12,051
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/trees/losses.py
43,44
33,52
line_search
MSELoss
44,52
44,52
class MSELoss: def __call__(self, y, y_pred): return np.mean((y - y_pred) ** 2) def base_estimator(self): return MeanBaseEstimator() def grad(self, y, y_pred): return -2 / len(y) * (y - y_pred) def line_search(self, y, y_pred, h_pred): FILL_FUNC_BODY
class MSELoss: def __call__(self, y, y_pred): return np.mean((y - y_pred) ** 2) def base_estimator(self): return MeanBaseEstimator() def grad(self, y, y_pred): return -2 / len(y) * (y - y_pred) def line_search(self, y, y_pred, h_pred): FILL_FUNC_BODY
# TODO: revise this Lp = np.sum((y - y_pred) * h_pred) Lpp = np.sum(h_pred * h_pred) # if we perfectly fit the residuals, use max step size return 1 if np.sum(Lpp) == 0 else Lp / Lpp
# TODO: revise this Lp = np.sum((y - y_pred) * h_pred) Lpp = np.sum(h_pred * h_pred) # if we perfectly fit the residuals, use max step size return 1 if np.sum(Lpp) == 0 else Lp / Lpp
37
121
92
213
import numpy as np ####################################################################### # Base Estimators # ####################################################################### class ClassProbEstimator: def fit(self, X, y): self.class_prob = y.sum...
import numpy as np ####################################################################### # Base Estimators # ####################################################################### class ClassProbEstimator: def fit(self, X, y): self.class_prob = y.sum...
12,052
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/trees/losses.py
22,23
18,33
predict
MeanBaseEstimator
23,33
23,33
class MeanBaseEstimator: def fit(self, X, y): self.avg = np.mean(y) def predict(self, X): FILL_FUNC_BODY
class MeanBaseEstimator: def fit(self, X, y): self.avg = np.mean(y) def predict(self, X): FILL_FUNC_BODY
pred = np.empty(X.shape[0], dtype=np.float64) pred.fill(self.avg) return pred ####################################################################### # Loss Functions # ####################################################################### ...
pred = np.empty(X.shape[0], dtype=np.float64) pred.fill(self.avg) return pred ####################################################################### # Loss Functions # ####################################################################### ...
13
53
71
124
import numpy as np ####################################################################### # Base Estimators # ####################################################################### class ClassProbEstimator: def fit(self, X, y): self.class_prob = y.sum...
import numpy as np ####################################################################### # Base Estimators # ####################################################################### class ClassProbEstimator: def fit(self, X, y): self.class_prob = y.sum...
12,053
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/trees/rf.py
5,6
1,100
bootstrap_sample
6,11
6,11
import numpy as np from .dt import DecisionTree def bootstrap_sample(X, Y): FILL_FUNC_BODYclass RandomForest: def __init__( self, n_trees, max_depth, n_feats, classifier=True, criterion="entropy" ): """ An ensemble (forest) of decision trees where each split is calculated using...
import numpy as np from .dt import DecisionTree def bootstrap_sample(X, Y): FILL_FUNC_BODYclass RandomForest: def __init__( self, n_trees, max_depth, n_feats, classifier=True, criterion="entropy" ): """ An ensemble (forest) of decision trees where each split is calculated using...
N, M = X.shape idxs = np.random.choice(N, N, replace=True) return X[idxs], Y[idxs]
N, M = X.shape idxs = np.random.choice(N, N, replace=True) return X[idxs], Y[idxs]
12
977
48
1,025
import numpy as np from .dt import DecisionTree def bootstrap_sample(X, Y): FILL_FUNC_BODYclass RandomForest: def __init__( self, n_trees, max_depth, n_feats, classifier=True, criterion="entropy" ): """ An ensemble (forest) of decision trees where each split is calculated using...
import numpy as np from .dt import DecisionTree def bootstrap_sample(X, Y): FILL_FUNC_BODYclass RandomForest: def __init__( self, n_trees, max_depth, n_feats, classifier=True, criterion="entropy" ): """ An ensemble (forest) of decision trees where each split is calculated using...
12,054
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/trees/rf.py
44,45
11,100
fit
RandomForest
49,61
45,61
class RandomForest: def __init__( self, n_trees, max_depth, n_feats, classifier=True, criterion="entropy" ): """ An ensemble (forest) of decision trees where each split is calculated using a random subset of the features in the input. Parameters ---------- ...
class RandomForest: def __init__( self, n_trees, max_depth, n_feats, classifier=True, criterion="entropy" ): """ An ensemble (forest) of decision trees where each split is calculated using a random subset of the features in the input. Parameters ---------- ...
self.trees = [] for _ in range(self.n_trees): X_samp, Y_samp = bootstrap_sample(X, Y) tree = DecisionTree( n_feats=self.n_feats, max_depth=self.max_depth, criterion=self.criterion, classifier=self.classifier, ...
""" Create `n_trees`-worth of bootstrapped samples from the training data and use each to fit a separate decision tree. """ self.trees = [] for _ in range(self.n_trees): X_samp, Y_samp = bootstrap_sample(X, Y) tree = DecisionTree( n...
23
825
137
962
import numpy as np from .dt import DecisionTree def bootstrap_sample(X, Y): N, M = X.shape idxs = np.random.choice(N, N, replace=True) return X[idxs], Y[idxs] class RandomForest: def __init__( self, n_trees, max_depth, n_feats, classifier=True, criterion="entropy" ): """ ...
import numpy as np from .dt import DecisionTree def bootstrap_sample(X, Y): N, M = X.shape idxs = np.random.choice(N, N, replace=True) return X[idxs], Y[idxs] class RandomForest: def __init__( self, n_trees, max_depth, n_feats, classifier=True, criterion="entropy" ): """ ...
12,055
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/utils/distance_metrics.py
79,80
1,133
minkowski
106,109
80,109
import numpy as np def euclidean(x, y): """ Compute the Euclidean (`L2`) distance between two real vectors Notes ----- The Euclidean distance between two vectors **x** and **y** is .. math:: d(\mathbf{x}, \mathbf{y}) = \sqrt{ \sum_i (x_i - y_i)^2 } Parameters ---------- ...
import numpy as np def euclidean(x, y): """ Compute the Euclidean (`L2`) distance between two real vectors Notes ----- The Euclidean distance between two vectors **x** and **y** is .. math:: d(\mathbf{x}, \mathbf{y}) = \sqrt{ \sum_i (x_i - y_i)^2 } Parameters ---------- ...
return np.sum(np.abs(x - y) ** p) ** (1 / p)
""" Compute the Minkowski-`p` distance between two real vectors. Notes ----- The Minkowski-`p` distance between two vectors **x** and **y** is .. math:: d(\mathbf{x}, \mathbf{y}) = \left( \sum_i |x_i - y_i|^p \\right)^{1/p} Parameters ---------- x,y : :py:class:`ndarray <...
10
1,088
29
1,117
import numpy as np def euclidean(x, y): """ Compute the Euclidean (`L2`) distance between two real vectors Notes ----- The Euclidean distance between two vectors **x** and **y** is .. math:: d(\mathbf{x}, \mathbf{y}) = \sqrt{ \sum_i (x_i - y_i)^2 } Parameters ---------- ...
import numpy as np def euclidean(x, y): """ Compute the Euclidean (`L2`) distance between two real vectors Notes ----- The Euclidean distance between two vectors **x** and **y** is .. math:: d(\mathbf{x}, \mathbf{y}) = \sqrt{ \sum_i (x_i - y_i)^2 } Parameters ---------- ...
12,056
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/utils/misc.py
5,6
1,25
logsumexp
10,16
6,16
"""Miscellaneous utility functions""" import numpy as np def logsumexp(log_probs, axis=None): FILL_FUNC_BODYdef log_gaussian_pdf(x_i, mu, sigma): """Compute log N(x_i | mu, sigma)""" n = len(mu) a = n * np.log(2 * np.pi) _, b = np.linalg.slogdet(sigma) y = np.linalg.solve(sigma, x_i - mu) c =...
"""Miscellaneous utility functions""" import numpy as np def logsumexp(log_probs, axis=None): """ Redefine scipy.special.logsumexp see: http://bayesjumping.net/log-sum-exp-trick/ """ FILL_FUNC_BODYdef log_gaussian_pdf(x_i, mu, sigma): """Compute log N(x_i | mu, sigma)""" n = len(mu) a = n ...
_max = np.max(log_probs) ds = log_probs - _max exp_sum = np.exp(ds).sum(axis=axis) return _max + np.log(exp_sum)
""" Redefine scipy.special.logsumexp see: http://bayesjumping.net/log-sum-exp-trick/ """ _max = np.max(log_probs) ds = log_probs - _max exp_sum = np.exp(ds).sum(axis=axis) return _max + np.log(exp_sum)
15
214
65
279
"""Miscellaneous utility functions""" import numpy as np def logsumexp(log_probs, axis=None): FILL_FUNC_BODYdef log_gaussian_pdf(x_i, mu, sigma): """Compute log N(x_i | mu, sigma)""" n = len(mu) a = n * np.log(2 * np.pi) _, b = np.linalg.slogdet(sigma) y = np.linalg.solve(sigma, x_i - mu) c =...
"""Miscellaneous utility functions""" import numpy as np def logsumexp(log_probs, axis=None): """ Redefine scipy.special.logsumexp see: http://bayesjumping.net/log-sum-exp-trick/ """ FILL_FUNC_BODYdef log_gaussian_pdf(x_i, mu, sigma): """Compute log N(x_i | mu, sigma)""" n = len(mu) a = n ...
12,057
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/utils/testing.py
99,100
1,144
random_paragraph
105,142
100,142
"""Utilities for writing unit tests""" import numbers import numpy as np ####################################################################### # Assertions # ####################################################################### def is_symmetric(X): ""...
"""Utilities for writing unit tests""" import numbers import numpy as np ####################################################################### # Assertions # ####################################################################### def is_symmetric(X): ""...
if vocab is None: vocab = [ "at", "stet", "accusam", "aliquyam", "clita", "lorem", "ipsum", "dolor", "dolore", "dolores", "sit", "amet", "consetetur", ...
""" Generate a random paragraph consisting of `n_words` words. If `vocab` is not None, words will be drawn at random from this list. Otherwise, words will be sampled uniformly from a collection of 26 Latin words. """ if vocab is None: vocab = [ "at", "stet", ...
46
1,030
265
1,295
"""Utilities for writing unit tests""" import numbers import numpy as np ####################################################################### # Assertions # ####################################################################### def is_symmetric(X): ""...
"""Utilities for writing unit tests""" import numbers import numpy as np ####################################################################### # Assertions # ####################################################################### def is_symmetric(X): ""...
12,058
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml
/home/hieuvd/dung_repo/raw/stars_01/ddbourgin_numpy-ml/numpy-ml/numpy_ml/utils/windows.py
108,109
1,157
generalized_cosine
139,145
109,145
import numpy as np def blackman_harris(window_len, symmetric=False): """ The Blackman-Harris window. Notes ----- The Blackman-Harris window is an instance of the more general class of cosine-sum windows where `K=3`. Additional coefficients extend the Hamming window to further minimize the...
import numpy as np def blackman_harris(window_len, symmetric=False): """ The Blackman-Harris window. Notes ----- The Blackman-Harris window is an instance of the more general class of cosine-sum windows where `K=3`. Additional coefficients extend the Hamming window to further minimize the...
window_len += 1 if not symmetric else 0 entries = np.linspace(-np.pi, np.pi, window_len) # (-1)^k * 2pi*n / window_len window = np.sum([ak * np.cos(k * entries) for k, ak in enumerate(coefs)], axis=0) return window[:-1] if not symmetric else window
""" The generalized cosine family of window functions. Notes ----- The generalized cosine window is a simple weighted sum of cosine terms. For :math:`n \in \{0, \ldots, \\text{window_len} \}`: .. math:: \\text{GCW}(n) = \sum_{k=0}^K (-1)^k a_k \cos\left(\\frac{2 \pi k n}{\\text{w...
39
1,567
108
1,675
import numpy as np def blackman_harris(window_len, symmetric=False): """ The Blackman-Harris window. Notes ----- The Blackman-Harris window is an instance of the more general class of cosine-sum windows where `K=3`. Additional coefficients extend the Hamming window to further minimize the...
import numpy as np def blackman_harris(window_len, symmetric=False): """ The Blackman-Harris window. Notes ----- The Blackman-Harris window is an instance of the more general class of cosine-sum windows where `K=3`. Additional coefficients extend the Hamming window to further minimize the...
12,059
/home/hieuvd/dung_repo/raw/stars_01/deep-floyd_IF/IF
/home/hieuvd/dung_repo/raw/stars_01/deep-floyd_IF/IF/deepfloyd_if/modules/stage_I.py
27,31
8,51
embeddings_to_image
IFStageI
31,51
31,51
class IFStageI(IFBaseModule): stage = 'I' available_models = ['IF-I-M-v1.0', 'IF-I-L-v1.0', 'IF-I-XL-v1.0'] def __init__(self, *args, model_kwargs=None, pil_img_size=64, **kwargs): """ :param conf_or_path: :param device: :param cache_dir: :param use_auth_token: ...
class IFStageI(IFBaseModule): stage = 'I' available_models = ['IF-I-M-v1.0', 'IF-I-L-v1.0', 'IF-I-XL-v1.0'] def __init__(self, *args, model_kwargs=None, pil_img_size=64, **kwargs): """ :param conf_or_path: :param device: :param cache_dir: :param use_auth_token: ...
return super().embeddings_to_image( t5_embs=t5_embs, style_t5_embs=style_t5_embs, positive_t5_embs=positive_t5_embs, negative_t5_embs=negative_t5_embs, batch_repeat=batch_repeat, dynamic_thresholding_p=dynamic_thresholding_p, d...
return super().embeddings_to_image( t5_embs=t5_embs, style_t5_embs=style_t5_embs, positive_t5_embs=positive_t5_embs, negative_t5_embs=negative_t5_embs, batch_repeat=batch_repeat, dynamic_thresholding_p=dynamic_thresholding_p, d...
20
414
250
664
# -*- coding: utf-8 -*- import accelerate from .base import IFBaseModule from ..model import UNetModel class IFStageI(IFBaseModule): stage = 'I' available_models = ['IF-I-M-v1.0', 'IF-I-L-v1.0', 'IF-I-XL-v1.0'] def __init__(self, *args, model_kwargs=None, pil_img_size=64, **kwargs): """ ...
# -*- coding: utf-8 -*- import accelerate from .base import IFBaseModule from ..model import UNetModel class IFStageI(IFBaseModule): stage = 'I' available_models = ['IF-I-M-v1.0', 'IF-I-L-v1.0', 'IF-I-XL-v1.0'] def __init__(self, *args, model_kwargs=None, pil_img_size=64, **kwargs): """ ...
12,060
/home/hieuvd/dung_repo/raw/stars_01/deep-floyd_IF/IF
/home/hieuvd/dung_repo/raw/stars_01/deep-floyd_IF/IF/deepfloyd_if/modules/stage_II.py
21,26
8,47
embeddings_to_image
IFStageII
26,47
26,47
class IFStageII(IFBaseModule): stage = 'II' available_models = ['IF-II-M-v1.0', 'IF-II-L-v1.0'] def __init__(self, *args, model_kwargs=None, pil_img_size=256, **kwargs): super().__init__(*args, pil_img_size=pil_img_size, **kwargs) model_params = dict(self.conf.params) model_params.u...
class IFStageII(IFBaseModule): stage = 'II' available_models = ['IF-II-M-v1.0', 'IF-II-L-v1.0'] def __init__(self, *args, model_kwargs=None, pil_img_size=256, **kwargs): super().__init__(*args, pil_img_size=pil_img_size, **kwargs) model_params = dict(self.conf.params) model_params.u...
return super().embeddings_to_image( t5_embs=t5_embs, low_res=low_res, style_t5_embs=style_t5_embs, positive_t5_embs=positive_t5_embs, negative_t5_embs=negative_t5_embs, batch_repeat=batch_repeat, aug_level=aug_level, ...
return super().embeddings_to_image( t5_embs=t5_embs, low_res=low_res, style_t5_embs=style_t5_embs, positive_t5_embs=positive_t5_embs, negative_t5_embs=negative_t5_embs, batch_repeat=batch_repeat, aug_level=aug_level, ...
22
397
271
668
# -*- coding: utf-8 -*- import accelerate from .base import IFBaseModule from ..model import SuperResUNetModel class IFStageII(IFBaseModule): stage = 'II' available_models = ['IF-II-M-v1.0', 'IF-II-L-v1.0'] def __init__(self, *args, model_kwargs=None, pil_img_size=256, **kwargs): super().__init_...
# -*- coding: utf-8 -*- import accelerate from .base import IFBaseModule from ..model import SuperResUNetModel class IFStageII(IFBaseModule): stage = 'II' available_models = ['IF-II-M-v1.0', 'IF-II-L-v1.0'] def __init__(self, *args, model_kwargs=None, pil_img_size=256, **kwargs): super().__init_...
12,061
/home/hieuvd/dung_repo/raw/stars_01/deep-floyd_IF/IF
/home/hieuvd/dung_repo/raw/stars_01/deep-floyd_IF/IF/deepfloyd_if/modules/stage_III.py
21,26
8,48
embeddings_to_image
IFStageIII
26,48
26,48
class IFStageIII(IFBaseModule): available_models = ['IF-III-L-v1.0'] def __init__(self, *args, model_kwargs=None, pil_img_size=1024, **kwargs): super().__init__(*args, pil_img_size=pil_img_size, **kwargs) model_params = dict(self.conf.params) model_params.update(model_kwargs or {}) ...
class IFStageIII(IFBaseModule): available_models = ['IF-III-L-v1.0'] def __init__(self, *args, model_kwargs=None, pil_img_size=1024, **kwargs): super().__init__(*args, pil_img_size=pil_img_size, **kwargs) model_params = dict(self.conf.params) model_params.update(model_kwargs or {}) ...
return super().embeddings_to_image( t5_embs=t5_embs, low_res=low_res, style_t5_embs=style_t5_embs, positive_t5_embs=positive_t5_embs, negative_t5_embs=negative_t5_embs, batch_repeat=batch_repeat, aug_level=aug_level, ...
return super().embeddings_to_image( t5_embs=t5_embs, low_res=low_res, style_t5_embs=style_t5_embs, positive_t5_embs=positive_t5_embs, negative_t5_embs=negative_t5_embs, batch_repeat=batch_repeat, aug_level=aug_level, ...
23
385
284
669
# -*- coding: utf-8 -*- import accelerate from .base import IFBaseModule from ..model import SuperResUNetModel class IFStageIII(IFBaseModule): available_models = ['IF-III-L-v1.0'] def __init__(self, *args, model_kwargs=None, pil_img_size=1024, **kwargs): super().__init__(*args, pil_img_size=pil_img...
# -*- coding: utf-8 -*- import accelerate from .base import IFBaseModule from ..model import SuperResUNetModel class IFStageIII(IFBaseModule): available_models = ['IF-III-L-v1.0'] def __init__(self, *args, model_kwargs=None, pil_img_size=1024, **kwargs): super().__init__(*args, pil_img_size=pil_img...
12,063
/home/hieuvd/dung_repo/raw/stars_01/deep-floyd_IF/IF
/home/hieuvd/dung_repo/raw/stars_01/deep-floyd_IF/IF/deepfloyd_if/modules/utils.py
17,18
1,24
clip_process_generations
18,24
18,24
# -*- coding: utf-8 -*- import numpy as np import torchvision.transforms as T def predict_proba(X, weights, biases): logits = X @ weights.T + biases proba = np.where(logits >= 0, 1 / (1 + np.exp(-logits)), np.exp(logits) / (1 + np.exp(logits))) return proba.T def load_model_weights(path): model_weig...
# -*- coding: utf-8 -*- import numpy as np import torchvision.transforms as T def predict_proba(X, weights, biases): logits = X @ weights.T + biases proba = np.where(logits >= 0, 1 / (1 + np.exp(-logits)), np.exp(logits) / (1 + np.exp(logits))) return proba.T def load_model_weights(path): model_weig...
min_size = min(generations.shape[-2:]) return T.Compose([ T.CenterCrop(min_size), T.Resize(224, interpolation=T.InterpolationMode.BICUBIC, antialias=True), T.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)), ])(generations)
min_size = min(generations.shape[-2:]) return T.Compose([ T.CenterCrop(min_size), T.Resize(224, interpolation=T.InterpolationMode.BICUBIC, antialias=True), T.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)), ])(generations)
16
179
158
337
# -*- coding: utf-8 -*- import numpy as np import torchvision.transforms as T def predict_proba(X, weights, biases): logits = X @ weights.T + biases proba = np.where(logits >= 0, 1 / (1 + np.exp(-logits)), np.exp(logits) / (1 + np.exp(logits))) return proba.T def load_model_weights(path): model_weig...
# -*- coding: utf-8 -*- import numpy as np import torchvision.transforms as T def predict_proba(X, weights, biases): logits = X @ weights.T + biases proba = np.where(logits >= 0, 1 / (1 + np.exp(-logits)), np.exp(logits) / (1 + np.exp(logits))) return proba.T def load_model_weights(path): model_weig...
12,064
/home/hieuvd/dung_repo/raw/stars_01/deep-floyd_IF/IF
/home/hieuvd/dung_repo/raw/stars_01/deep-floyd_IF/IF/deepfloyd_if/pipelines/super_resolution.py
9,24
1,67
super_resolution
24,67
24,67
# -*- coding: utf-8 -*- from datetime import datetime import PIL from .utils import _prepare_pil_image def super_resolution( t5, if_III=None, *, support_pil_img, prompt=None, negative_prompt=None, seed=None, if_III_kwargs=None, progress=True, img_size=256, img_scale=4.0, ...
# -*- coding: utf-8 -*- from datetime import datetime import PIL from .utils import _prepare_pil_image def super_resolution( t5, if_III=None, *, support_pil_img, prompt=None, negative_prompt=None, seed=None, if_III_kwargs=None, progress=True, img_size=256, img_scale=4.0, ...
assert isinstance(support_pil_img, PIL.Image.Image) assert img_size % 8 == 0 if seed is None: seed = int((datetime.utcnow().timestamp() * 10 ** 6) % (2 ** 32 - 1)) if prompt is not None: t5_embs = t5.get_text_embeddings(prompt) else: t5_embs = t5.get_text_embeddings('') ...
assert isinstance(support_pil_img, PIL.Image.Image) assert img_size % 8 == 0 if seed is None: seed = int((datetime.utcnow().timestamp() * 10 ** 6) % (2 ** 32 - 1)) if prompt is not None: t5_embs = t5.get_text_embeddings(prompt) else: t5_embs = t5.get_text_embeddings('') ...
116
158
545
703
# -*- coding: utf-8 -*- from datetime import datetime import PIL from .utils import _prepare_pil_image def super_resolution( t5, if_III=None, *, support_pil_img, prompt=None, negative_prompt=None, seed=None, if_III_kwargs=None, progress=True, img_size=256, img_scale=4.0, ...
# -*- coding: utf-8 -*- from datetime import datetime import PIL from .utils import _prepare_pil_image def super_resolution( t5, if_III=None, *, support_pil_img, prompt=None, negative_prompt=None, seed=None, if_III_kwargs=None, progress=True, img_size=256, img_scale=4.0, ...
12,065
/home/hieuvd/dung_repo/raw/stars_01/deep-floyd_IF/IF
/home/hieuvd/dung_repo/raw/stars_01/deep-floyd_IF/IF/setup.py
13,14
1,58
get_requirements
14,29
14,29
# -*- coding: utf-8 -*- import os import re from setuptools import setup def read(filename): with open(os.path.join(os.path.dirname(__file__), filename)) as f: file_content = f.read() return file_content def get_requirements(): FILL_FUNC_BODYdef get_links(): return [ requirement for requ...
# -*- coding: utf-8 -*- import os import re from setuptools import setup def read(filename): with open(os.path.join(os.path.dirname(__file__), filename)) as f: file_content = f.read() return file_content def get_requirements(): FILL_FUNC_BODYdef get_links(): return [ requirement for requ...
requirements = [] for requirement in read('requirements.txt').splitlines(): if requirement.startswith('git+') or requirement.startswith('svn+') or requirement.startswith('hg+'): parsed_requires = re.findall(r'#egg=([\w\d\.]+)-([\d\.]+)$', requirement) if parsed_requires: ...
requirements = [] for requirement in read('requirements.txt').splitlines(): if requirement.startswith('git+') or requirement.startswith('svn+') or requirement.startswith('hg+'): parsed_requires = re.findall(r'#egg=([\w\d\.]+)-([\d\.]+)$', requirement) if parsed_requires: ...
46
444
210
654
# -*- coding: utf-8 -*- import os import re from setuptools import setup def read(filename): with open(os.path.join(os.path.dirname(__file__), filename)) as f: file_content = f.read() return file_content def get_requirements(): FILL_FUNC_BODYdef get_links(): return [ requirement for requ...
# -*- coding: utf-8 -*- import os import re from setuptools import setup def read(filename): with open(os.path.join(os.path.dirname(__file__), filename)) as f: file_content = f.read() return file_content def get_requirements(): FILL_FUNC_BODYdef get_links(): return [ requirement for requ...
12,234
/home/hieuvd/dung_repo/raw/stars_01/drivendata_cookiecutter-data-science/cookiecutter-data-science
/home/hieuvd/dung_repo/raw/stars_01/drivendata_cookiecutter-data-science/cookiecutter-data-science/hooks/pre_gen_project.py
1,2
1,23
deprecation_warning
2,22
2,22
def deprecation_warning(): FILL_FUNC_BODYdeprecation_warning()
def deprecation_warning(): FILL_FUNC_BODYdeprecation_warning()
print(""" ============================================================================= *** DEPRECATION WARNING *** Cookiecutter data science is moving to v2 soon, which will entail using the command `ccds ...` rather than `cookiecutter ...`. The cookiecutter command will continue to work, and this version of the...
print(""" ============================================================================= *** DEPRECATION WARNING *** Cookiecutter data science is moving to v2 soon, which will entail using the command `ccds ...` rather than `cookiecutter ...`. The cookiecutter command will continue to work, and this version of the...
83
25
196
221
def deprecation_warning(): FILL_FUNC_BODYdeprecation_warning()
def deprecation_warning(): FILL_FUNC_BODYdeprecation_warning()
12,434
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/_exception_handler.py
34,35
1,88
wrap_app_handling_exceptions
35,88
35,88
from __future__ import annotations import typing from starlette._utils import is_async_callable from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.types import ( ASGIApp, ExceptionHandler, HTTPExceptionHa...
from __future__ import annotations import typing from starlette._utils import is_async_callable from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.types import ( ASGIApp, ExceptionHandler, HTTPExceptionHa...
exception_handlers: ExceptionHandlers status_handlers: StatusHandlers try: exception_handlers, status_handlers = conn.scope["starlette.exception_handlers"] except KeyError: exception_handlers, status_handlers = {}, {} async def wrapped_app(scope: Scope, receive: Receive, send: Send)...
exception_handlers: ExceptionHandlers status_handlers: StatusHandlers try: exception_handlers, status_handlers = conn.scope["starlette.exception_handlers"] except KeyError: exception_handlers, status_handlers = {}, {} async def wrapped_app(scope: Scope, receive: Receive, send: Send)...
149
277
528
805
from __future__ import annotations import typing from starlette._utils import is_async_callable from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.types import ( ASGIApp, ExceptionHandler, HTTPExceptionHa...
from __future__ import annotations import typing from starlette._utils import is_async_callable from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.types import ( ASGIApp, ExceptionHandler, HTTPExceptionHa...
12,435
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/authentication.py
23,24
1,156
has_required_scope
24,30
24,30
from __future__ import annotations import functools import inspect import sys import typing from urllib.parse import urlencode if sys.version_info >= (3, 10): # pragma: no cover from typing import ParamSpec else: # pragma: no cover from typing_extensions import ParamSpec from starlette._utils import is_asy...
from __future__ import annotations import functools import inspect import sys import typing from urllib.parse import urlencode if sys.version_info >= (3, 10): # pragma: no cover from typing import ParamSpec else: # pragma: no cover from typing_extensions import ParamSpec from starlette._utils import is_asy...
for scope in scopes: if scope not in conn.auth.scopes: return False return True
for scope in scopes: if scope not in conn.auth.scopes: return False return True
13
1,407
37
1,444
from __future__ import annotations import functools import inspect import sys import typing from urllib.parse import urlencode if sys.version_info >= (3, 10): # pragma: no cover from typing import ParamSpec else: # pragma: no cover from typing_extensions import ParamSpec from starlette._utils import is_asy...
from __future__ import annotations import functools import inspect import sys import typing from urllib.parse import urlencode if sys.version_info >= (3, 10): # pragma: no cover from typing import ParamSpec else: # pragma: no cover from typing_extensions import ParamSpec from starlette._utils import is_asy...
12,436
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/authentication.py
110,113
109,116
authenticate
AuthenticationBackend
113,116
113,116
class AuthenticationBackend: async def authenticate( self, conn: HTTPConnection ) -> tuple[AuthCredentials, BaseUser] | None: FILL_FUNC_BODY
class AuthenticationBackend: async def authenticate( self, conn: HTTPConnection ) -> tuple[AuthCredentials, BaseUser] | None: FILL_FUNC_BODY
raise NotImplementedError() # pragma: no cover
raise NotImplementedError() # pragma: no cover
6
49
21
70
from __future__ import annotations import functools import inspect import sys import typing from urllib.parse import urlencode if sys.version_info >= (3, 10): # pragma: no cover from typing import ParamSpec else: # pragma: no cover from typing_extensions import ParamSpec from starlette._utils import is_asy...
from __future__ import annotations import functools import inspect import sys import typing from urllib.parse import urlencode if sys.version_info >= (3, 10): # pragma: no cover from typing import ParamSpec else: # pragma: no cover from typing_extensions import ParamSpec from starlette._utils import is_asy...
12,437
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/authentication.py
130,132
121,135
identity
BaseUser
132,135
132,135
class BaseUser: @property def is_authenticated(self) -> bool: raise NotImplementedError() # pragma: no cover @property def display_name(self) -> str: raise NotImplementedError() # pragma: no cover @property def identity(self) -> str: FILL_FUNC_BODY
class BaseUser: @property def is_authenticated(self) -> bool: raise NotImplementedError() # pragma: no cover @property def display_name(self) -> str: raise NotImplementedError() # pragma: no cover @property def identity(self) -> str: FILL_FUNC_BODY
raise NotImplementedError() # pragma: no cover
raise NotImplementedError() # pragma: no cover
6
100
21
121
from __future__ import annotations import functools import inspect import sys import typing from urllib.parse import urlencode if sys.version_info >= (3, 10): # pragma: no cover from typing import ParamSpec else: # pragma: no cover from typing_extensions import ParamSpec from starlette._utils import is_asy...
from __future__ import annotations import functools import inspect import sys import typing from urllib.parse import urlencode if sys.version_info >= (3, 10): # pragma: no cover from typing import ParamSpec else: # pragma: no cover from typing_extensions import ParamSpec from starlette._utils import is_asy...
12,438
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/authentication.py
139,141
135,148
is_authenticated
SimpleUser
141,143
141,143
class SimpleUser(BaseUser): def __init__(self, username: str) -> None: self.username = username @property def is_authenticated(self) -> bool: FILL_FUNC_BODY @property def display_name(self) -> str: return self.username
class SimpleUser(BaseUser): def __init__(self, username: str) -> None: self.username = username @property def is_authenticated(self) -> bool: FILL_FUNC_BODY @property def display_name(self) -> str: return self.username
return True
return True
2
86
7
93
from __future__ import annotations import functools import inspect import sys import typing from urllib.parse import urlencode if sys.version_info >= (3, 10): # pragma: no cover from typing import ParamSpec else: # pragma: no cover from typing_extensions import ParamSpec from starlette._utils import is_asy...
from __future__ import annotations import functools import inspect import sys import typing from urllib.parse import urlencode if sys.version_info >= (3, 10): # pragma: no cover from typing import ParamSpec else: # pragma: no cover from typing_extensions import ParamSpec from starlette._utils import is_asy...
12,439
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/authentication.py
153,155
148,156
display_name
UnauthenticatedUser
155,156
155,156
class UnauthenticatedUser(BaseUser): @property def is_authenticated(self) -> bool: return False @property def display_name(self) -> str: FILL_FUNC_BODY
class UnauthenticatedUser(BaseUser): @property def is_authenticated(self) -> bool: return False @property def display_name(self) -> str: FILL_FUNC_BODY
return ""
return ""
2
62
5
67
from __future__ import annotations import functools import inspect import sys import typing from urllib.parse import urlencode if sys.version_info >= (3, 10): # pragma: no cover from typing import ParamSpec else: # pragma: no cover from typing_extensions import ParamSpec from starlette._utils import is_asy...
from __future__ import annotations import functools import inspect import sys import typing from urllib.parse import urlencode if sys.version_info >= (3, 10): # pragma: no cover from typing import ParamSpec else: # pragma: no cover from typing_extensions import ParamSpec from starlette._utils import is_asy...
12,440
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/background.py
37,40
33,46
add_task
BackgroundTasks
40,43
40,43
class BackgroundTasks(BackgroundTask): def __init__(self, tasks: typing.Sequence[BackgroundTask] | None = None): self.tasks = list(tasks) if tasks else [] def add_task( self, func: typing.Callable[P, typing.Any], *args: P.args, **kwargs: P.kwargs ) -> None: FILL_FUNC_BODY async def __cal...
class BackgroundTasks(BackgroundTask): def __init__(self, tasks: typing.Sequence[BackgroundTask] | None = None): self.tasks = list(tasks) if tasks else [] def add_task( self, func: typing.Callable[P, typing.Any], *args: P.args, **kwargs: P.kwargs ) -> None: FILL_FUNC_BODY async def __cal...
task = BackgroundTask(func, *args, **kwargs) self.tasks.append(task)
task = BackgroundTask(func, *args, **kwargs) self.tasks.append(task)
6
130
31
161
from __future__ import annotations import sys import typing if sys.version_info >= (3, 10): # pragma: no cover from typing import ParamSpec else: # pragma: no cover from typing_extensions import ParamSpec from starlette._utils import is_async_callable from starlette.concurrency import run_in_threadpool P ...
from __future__ import annotations import sys import typing if sys.version_info >= (3, 10): # pragma: no cover from typing import ParamSpec else: # pragma: no cover from typing_extensions import ParamSpec from starlette._utils import is_async_callable from starlette.concurrency import run_in_threadpool P ...
12,441
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/concurrency.py
19,20
1,68
run_until_first_complete
20,36
20,36
from __future__ import annotations import functools import sys import typing import warnings import anyio.to_thread if sys.version_info >= (3, 10): # pragma: no cover from typing import ParamSpec else: # pragma: no cover from typing_extensions import ParamSpec P = ParamSpec("P") T = typing.TypeVar("T") ...
from __future__ import annotations import functools import sys import typing import warnings import anyio.to_thread if sys.version_info >= (3, 10): # pragma: no cover from typing import ParamSpec else: # pragma: no cover from typing_extensions import ParamSpec P = ParamSpec("P") T = typing.TypeVar("T") ...
warnings.warn( "run_until_first_complete is deprecated " "and will be removed in a future version.", DeprecationWarning, ) async with anyio.create_task_group() as task_group: async def run(func: typing.Callable[[], typing.Coroutine]) -> None: # type: ignore[type-arg] # no...
warnings.warn( "run_until_first_complete is deprecated " "and will be removed in a future version.", DeprecationWarning, ) async with anyio.create_task_group() as task_group: async def run(func: typing.Callable[[], typing.Coroutine]) -> None: # type: ignore[type-arg] # no...
44
460
176
636
from __future__ import annotations import functools import sys import typing import warnings import anyio.to_thread if sys.version_info >= (3, 10): # pragma: no cover from typing import ParamSpec else: # pragma: no cover from typing_extensions import ParamSpec P = ParamSpec("P") T = typing.TypeVar("T") ...
from __future__ import annotations import functools import sys import typing import warnings import anyio.to_thread if sys.version_info >= (3, 10): # pragma: no cover from typing import ParamSpec else: # pragma: no cover from typing_extensions import ParamSpec P = ParamSpec("P") T = typing.TypeVar("T") ...
12,442
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/config.py
103,109
54,154
get
Config
109,120
109,120
class Config: def __init__( self, env_file: str | Path | None = None, environ: typing.Mapping[str, str] = environ, env_prefix: str = "", ) -> None: self.environ = environ self.env_prefix = env_prefix self.file_values: dict[str, str] = {} if env_fil...
class Config: def __init__( self, env_file: str | Path | None = None, environ: typing.Mapping[str, str] = environ, env_prefix: str = "", ) -> None: self.environ = environ self.env_prefix = env_prefix self.file_values: dict[str, str] = {} if env_fil...
key = self.env_prefix + key if key in self.environ: value = self.environ[key] return self._perform_cast(key, value, cast) if key in self.file_values: value = self.file_values[key] return self._perform_cast(key, value, cast) if default is no...
key = self.env_prefix + key if key in self.environ: value = self.environ[key] return self._perform_cast(key, value, cast) if key in self.file_values: value = self.file_values[key] return self._perform_cast(key, value, cast) if default is no...
45
897
144
1,041
from __future__ import annotations import os import typing import warnings from pathlib import Path class undefined: pass class EnvironError(Exception): pass class Environ(typing.MutableMapping[str, str]): def __init__(self, environ: typing.MutableMapping[str, str] = os.environ): self._enviro...
from __future__ import annotations import os import typing import warnings from pathlib import Path class undefined: pass class EnvironError(Exception): pass class Environ(typing.MutableMapping[str, str]): def __init__(self, environ: typing.MutableMapping[str, str] = os.environ): self._enviro...
12,443
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/convertors.py
88,89
1,90
register_url_convertor
89,90
89,90
from __future__ import annotations import math import typing import uuid T = typing.TypeVar("T") class Convertor(typing.Generic[T]): regex: typing.ClassVar[str] = "" def convert(self, value: str) -> T: raise NotImplementedError() # pragma: no cover def to_string(self, value: T) -> str: ...
from __future__ import annotations import math import typing import uuid T = typing.TypeVar("T") class Convertor(typing.Generic[T]): regex: typing.ClassVar[str] = "" def convert(self, value: str) -> T: raise NotImplementedError() # pragma: no cover def to_string(self, value: T) -> str: ...
CONVERTOR_TYPES[key] = convertor
CONVERTOR_TYPES[key] = convertor
3
797
17
814
from __future__ import annotations import math import typing import uuid T = typing.TypeVar("T") class Convertor(typing.Generic[T]): regex: typing.ClassVar[str] = "" def convert(self, value: str) -> T: raise NotImplementedError() # pragma: no cover def to_string(self, value: T) -> str: ...
from __future__ import annotations import math import typing import uuid T = typing.TypeVar("T") class Convertor(typing.Generic[T]): regex: typing.ClassVar[str] = "" def convert(self, value: str) -> T: raise NotImplementedError() # pragma: no cover def to_string(self, value: T) -> str: ...
12,444
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/convertors.py
13,14
10,20
convert
Convertor
14,16
14,16
class Convertor(typing.Generic[T]): regex: typing.ClassVar[str] = "" def convert(self, value: str) -> T: FILL_FUNC_BODY def to_string(self, value: T) -> str: raise NotImplementedError() # pragma: no cover
class Convertor(typing.Generic[T]): regex: typing.ClassVar[str] = "" def convert(self, value: str) -> T: FILL_FUNC_BODY def to_string(self, value: T) -> str: raise NotImplementedError() # pragma: no cover
raise NotImplementedError() # pragma: no cover
raise NotImplementedError() # pragma: no cover
6
87
19
106
from __future__ import annotations import math import typing import uuid T = typing.TypeVar("T") class Convertor(typing.Generic[T]): regex: typing.ClassVar[str] = "" def convert(self, value: str) -> T: FILL_FUNC_BODY def to_string(self, value: T) -> str: raise NotImplementedError() # pragma: no...
from __future__ import annotations import math import typing import uuid T = typing.TypeVar("T") class Convertor(typing.Generic[T]): regex: typing.ClassVar[str] = "" def convert(self, value: str) -> T: FILL_FUNC_BODY def to_string(self, value: T) -> str: raise NotImplementedError() # pragma: no...
12,445
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/convertors.py
61,62
55,69
to_string
FloatConvertor
62,69
62,69
class FloatConvertor(Convertor[float]): regex = r"[0-9]+(\.[0-9]+)?" def convert(self, value: str) -> float: return float(value) def to_string(self, value: float) -> str: FILL_FUNC_BODY
class FloatConvertor(Convertor[float]): regex = r"[0-9]+(\.[0-9]+)?" def convert(self, value: str) -> float: return float(value) def to_string(self, value: float) -> str: FILL_FUNC_BODY
value = float(value) assert value >= 0.0, "Negative floats are not supported" assert not math.isnan(value), "NaN values are not supported" assert not math.isinf(value), "Infinite values are not supported" return ("%0.20f" % value).rstrip("0").rstrip(".")
value = float(value) assert value >= 0.0, "Negative floats are not supported" assert not math.isnan(value), "NaN values are not supported" assert not math.isinf(value), "Infinite values are not supported" return ("%0.20f" % value).rstrip("0").rstrip(".")
32
85
96
181
from __future__ import annotations import math import typing import uuid T = typing.TypeVar("T") class Convertor(typing.Generic[T]): regex: typing.ClassVar[str] = "" def convert(self, value: str) -> T: raise NotImplementedError() # pragma: no cover def to_string(self, value: T) -> str: ...
from __future__ import annotations import math import typing import uuid T = typing.TypeVar("T") class Convertor(typing.Generic[T]): regex: typing.ClassVar[str] = "" def convert(self, value: str) -> T: raise NotImplementedError() # pragma: no cover def to_string(self, value: T) -> str: ...
12,446
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/convertors.py
49,50
43,55
to_string
IntegerConvertor
50,55
50,55
class IntegerConvertor(Convertor[int]): regex = "[0-9]+" def convert(self, value: str) -> int: return int(value) def to_string(self, value: int) -> str: FILL_FUNC_BODY
class IntegerConvertor(Convertor[int]): regex = "[0-9]+" def convert(self, value: str) -> int: return int(value) def to_string(self, value: int) -> str: FILL_FUNC_BODY
value = int(value) assert value >= 0, "Negative integers are not supported" return str(value)
value = int(value) assert value >= 0, "Negative integers are not supported" return str(value)
14
74
37
111
from __future__ import annotations import math import typing import uuid T = typing.TypeVar("T") class Convertor(typing.Generic[T]): regex: typing.ClassVar[str] = "" def convert(self, value: str) -> T: raise NotImplementedError() # pragma: no cover def to_string(self, value: T) -> str: ...
from __future__ import annotations import math import typing import uuid T = typing.TypeVar("T") class Convertor(typing.Generic[T]): regex: typing.ClassVar[str] = "" def convert(self, value: str) -> T: raise NotImplementedError() # pragma: no cover def to_string(self, value: T) -> str: ...
12,447
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/convertors.py
36,37
33,43
convert
PathConvertor
37,39
37,39
class PathConvertor(Convertor[str]): regex = ".*" def convert(self, value: str) -> str: FILL_FUNC_BODY def to_string(self, value: str) -> str: return str(value)
class PathConvertor(Convertor[str]): regex = ".*" def convert(self, value: str) -> str: FILL_FUNC_BODY def to_string(self, value: str) -> str: return str(value)
return str(value)
return str(value)
2
71
10
81
from __future__ import annotations import math import typing import uuid T = typing.TypeVar("T") class Convertor(typing.Generic[T]): regex: typing.ClassVar[str] = "" def convert(self, value: str) -> T: raise NotImplementedError() # pragma: no cover def to_string(self, value: T) -> str: ...
from __future__ import annotations import math import typing import uuid T = typing.TypeVar("T") class Convertor(typing.Generic[T]): regex: typing.ClassVar[str] = "" def convert(self, value: str) -> T: raise NotImplementedError() # pragma: no cover def to_string(self, value: T) -> str: ...
12,448
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/convertors.py
26,27
20,33
to_string
StringConvertor
27,33
27,33
class StringConvertor(Convertor[str]): regex = "[^/]+" def convert(self, value: str) -> str: return value def to_string(self, value: str) -> str: FILL_FUNC_BODY
class StringConvertor(Convertor[str]): regex = "[^/]+" def convert(self, value: str) -> str: return value def to_string(self, value: str) -> str: FILL_FUNC_BODY
value = str(value) assert "/" not in value, "May not contain path separators" assert value, "Must not be empty" return value
value = str(value) assert "/" not in value, "May not contain path separators" assert value, "Must not be empty" return value
21
70
48
118
from __future__ import annotations import math import typing import uuid T = typing.TypeVar("T") class Convertor(typing.Generic[T]): regex: typing.ClassVar[str] = "" def convert(self, value: str) -> T: raise NotImplementedError() # pragma: no cover def to_string(self, value: T) -> str: ...
from __future__ import annotations import math import typing import uuid T = typing.TypeVar("T") class Convertor(typing.Generic[T]): regex: typing.ClassVar[str] = "" def convert(self, value: str) -> T: raise NotImplementedError() # pragma: no cover def to_string(self, value: T) -> str: ...
12,449
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette
/home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/convertors.py
72,73
69,79
convert
UUIDConvertor
73,75
73,75
class UUIDConvertor(Convertor[uuid.UUID]): regex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" def convert(self, value: str) -> uuid.UUID: FILL_FUNC_BODY def to_string(self, value: uuid.UUID) -> str: return str(value)
class UUIDConvertor(Convertor[uuid.UUID]): regex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" def convert(self, value: str) -> uuid.UUID: FILL_FUNC_BODY def to_string(self, value: uuid.UUID) -> str: return str(value)
return uuid.UUID(value)
return uuid.UUID(value)
2
127
13
140
from __future__ import annotations import math import typing import uuid T = typing.TypeVar("T") class Convertor(typing.Generic[T]): regex: typing.ClassVar[str] = "" def convert(self, value: str) -> T: raise NotImplementedError() # pragma: no cover def to_string(self, value: T) -> str: ...
from __future__ import annotations import math import typing import uuid T = typing.TypeVar("T") class Convertor(typing.Generic[T]): regex: typing.ClassVar[str] = "" def convert(self, value: str) -> T: raise NotImplementedError() # pragma: no cover def to_string(self, value: T) -> str: ...