python_code stringlengths 0 992k | repo_name stringlengths 8 46 | file_path stringlengths 5 162 |
|---|---|---|
# Copyright (c) 2022 Agora
# Licensed under The MIT License [see LICENSE for details]
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
# NOTE: This is a mirror of the co... | zeta-main | zeta/nn/modules/xmoe/moe_layer.py |
# Copyright (c) 2022 Agora
# Licensed under The MIT License [see LICENSE for details]
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
# Implementation of Top2Gating des... | zeta-main | zeta/nn/modules/xmoe/routing.py |
from functools import partial
import torch
from torch.distributed.fsdp import (
FullyShardedDataParallel,
MixedPrecision,
BackwardPrefetch,
ShardingStrategy,
)
from torch.distributed.fsdp.wrap import (
transformer_auto_wrap_policy
)
def fsdp(
model: torch.nn.Module,
auto_wrap: bool = ... | zeta-main | zeta/training/fsdp.py |
from functools import partial
import torch
from accelerate import Accelerator
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import (
CheckpointImpl, apply_activation_checkpointing, checkpoint_wrapper)
def activation_checkpointing(
model: torch.nn.Module,
offload_to_cpu: bool = False... | zeta-main | zeta/training/activation_checkpoint.py |
from zeta.tokenizers.multi_modal_tokenizer import MultiModalTokenizer
from zeta.tokenizers.language_tokenizer import LanguageTokenizerGPTX
from zeta.training.train import Trainer, train
from zeta.optim.decoupled_optimizer import decoupled_optimizer
from zeta.optim.stable_adam import StableAdamWUnfused
from zeta.opti... | zeta-main | zeta/training/__init__.py |
import math
import os
from datetime import timedelta
import torch
from accelerate import Accelerator
from accelerate.utils import InitProcessGroupKwargs
from torch.utils.data import DataLoader
from tqdm import tqdm
from transformers import default_data_collator, set_seed
from zeta.training.dataloader import build_da... | zeta-main | zeta/training/train.py |
from itertools import chain
from datasets import load_dataset
from transformers import (AutoTokenizer)
def build_dataloaders(
seq_len: int = None,
num_cpu: int = None
):
"""
Build data loaders for training.
This function performs the following steps:
1. Load the tokenizer from the pre... | zeta-main | zeta/training/dataloader.py |
import torch
from accelerate import Accelerator
from transformers import (get_cosine_schedule_with_warmup,
get_linear_schedule_with_warmup)
def get_lr_scheduler_with_warmup(
optimizer: torch.optim.Optimizer,
scheduler_type: str,
num_warmup_steps: int,
max_train_steps: int,... | zeta-main | zeta/training/scheduler.py |
zeta-main | zeta/training/loss/__init__.py | |
import torch
import torch.nn.functional as F
import torch.nn as nn
import numpy as np
import logging
# Helpers
def one_hot_encoding(y_true, num_classes):
y_true_one_hot = torch.zeros(y_true.size(0), num_classes)
y_true_one_hot.scatter_(1, y_true.unsqueeze(1), 1)
return y_true_one_hot
def is_multi_label... | zeta-main | zeta/training/loss/nebula.py |
import torch
from torch import Tensor
from torch.optim.optimizer import Optimizer
from typing import List
class SophiaG(Optimizer):
"""
SophiaG optimizer class.
"""
def __init__(self, params, lr=1e-4, betas=(0.965, 0.99), rho = 0.04,
weight_decay=1e-1, *, maximize: bool = False,
capt... | zeta-main | zeta/optim/decoupled_sophia.py |
zeta-main | zeta/optim/__init__.py | |
import torch
class StableAdamWUnfused(torch.optim.Optimizer):
def __init__(
self,
params,
lr=0.002,
weight_decay=0.2,
betas=(0.9, 0.99),
eps=1e-8,
clip_thresh=1.0,
precision="amp_bfloat16",
custom_scalar=65536,
):
beta1, beta2 = ... | zeta-main | zeta/optim/stable_adam.py |
import bitsandbytes as bnb
import torch
from accelerate import Accelerator
from lion_pytorch import Lion
from torch.nn import LayerNorm
from torch.optim import AdamW
from zeta.optim.stable_adam import StableAdamWUnfused
def decoupled_optimizer(
model: torch.nn.Module,
learning_rate: float,
weight_deca... | zeta-main | zeta/optim/decoupled_optimizer.py |
import logging
import math
from typing import Callable, Optional, Tuple
import torch
from torch.optim.optimizer import Optimizer
log = logging.getLogger(__name__)
class DecoupledLionW(Optimizer):
"""
DecoupledLionW is an optimizer designed to improve training performance and convergence for deep learning ... | zeta-main | zeta/optim/decoupled_lion.py |
# Copyright (c) 2022 Agora
# Licensed under The MIT License [see LICENSE for details]
from zeta.utils.main import * | zeta-main | zeta/utils/__init__.py |
import math
from functools import partial, wraps
from math import ceil
import einops
import numpy as np
import torch
import torch.functional as F
import torch.nn as nn
from accelerate import Accelerator
from einops import rearrange
from PIL import Image
####
from torchvision import transforms as T
def exists(val):
... | zeta-main | zeta/utils/main.py |
from typing import Callable, Optional, Tuple, List
from beartype import beartype
from einops import Rearrange, Reduce
from torch import nn
from zeta.nn.architecture.transformer import FeedForward
from zeta.nn.attention.attend import Attend
from zeta.nn.modules.mbconv import MBConv, Residual
from zeta.utils.main impor... | zeta-main | zeta/models/max_vit.py |
#gene splice
| zeta-main | zeta/models/GeneSplice.py |
#modularize the decoder to accept any attemtion, dilated or multihead
import torch
from torch.nn import Module
import bitsandbytes
from zeta import DecoderConfig, Decoder
from zeta.utils.embedding import PositionalEmbedding
from transformers import AutoTokenizer
class LongNetTokenizer:
def __init__(self):
... | zeta-main | zeta/models/LongNet.py |
#the best llm ever made
from torch.nn import Module
from zeta.nn.architecture.auto_regressive_wrapper import AutoregressiveWrapper
from zeta.nn.architecture.transformer import (
Decoder,
Transformer,
)
class Andromeda(Module):
"""
Andromeda is a transformer-based model architecture. It initializes wi... | zeta-main | zeta/models/andromeda.py |
# Copyright (c) 2022 Agora
# Licensed under The MIT License [see LICENSE for details]
import torch
import torch.nn as nn
from zeta.nn.architecture.encoder import Encoder
from zeta.utils.embedding import (
PositionalEmbedding,
TextEmbedding,
VisionEmbedding,
)
from zeta.utils.module.multiway_network import... | zeta-main | zeta/models/BEiT3.py |
# Copyright (c) 2022 Agora
# Licensed under The MIT License [see LICENSE for details]
from zeta.models.gpt4 import GPT4, GPT4MultiModal
from zeta.models.andromeda import Andromeda
from zeta.models.palme import PalmE
from zeta.models.base import BaseModel | zeta-main | zeta/models/__init__.py |
zeta-main | zeta/models/Magneto.py | |
import torch
from zeta.nn.architecture.auto_regressive_wrapper import AutoregressiveWrapper
from zeta.nn.architecture.transformer import (
Decoder,
Encoder,
Transformer,
ViTransformerWrapper,
)
class PalmE(torch.nn.Module):
def __init__(self,
image_size=256,
pa... | zeta-main | zeta/models/palme.py |
from zeta.nn.architecture.transformer import Transformer, Decoder
from zeta.nn.architecture.auto_regressive_wrapper import AutoregressiveWrapper
class LLama2:
def __init__(
self,
num_tokens=50432,
max_seq_len=8192,
dim=2560,
depth=32,
dim_head=128,
head... | zeta-main | zeta/models/llama.py |
import torch
from einops import rearrange
from torch import nn
from zeta.nn.architecture.transformer import Encoder
def exists(val):
return val is not None
def divisible_by(num, den):
return (num % den) == 0
class ViT(nn.Module):
def __init__(self,
*,
image_size,
... | zeta-main | zeta/models/vit.py |
from abc import ABC, abstractmethod
class BaseModel(ABC):
def __init__(self, *args, **kwargs):
pass
def forward(self):
pass | zeta-main | zeta/models/base.py |
import torch
from torch import nn
from zeta.nn.architecture.transformer import (
Decoder,
Encoder,
Transformer,
ViTransformerWrapper,
)
from zeta.nn.architecture.auto_regressive_wrapper import AutoregressiveWrapper
class GPT4(nn.Module):
"""
GPT4 is a transformer-based model architecture. It... | zeta-main | zeta/models/gpt4.py |
import torch
from zeta import DecoderConfig, Decoder
from zeta.utils.embedding import PositionalEmbedding
from transformers import CLIPProcessor, CLIPModel, AutoTokenizer
from flamingo_pytorch import PerceiverResampler
from torch.nn import Module
import bitsandbytes
class KosmosTokenizer:
def __init__(self):
... | zeta-main | zeta/models/kosmos.py |
# implementation of a general rest algorithm to plug in and play with any model on zeta
# need a maintainer for this directory. | zeta-main | zeta/rl/rest.py |
zeta-main | zeta/rl/__init__.py | |
import copy
from pathlib import Path
import torch
import torch.nn.functional as F
from beartype import beatype
from einops import rearrange, repeat
from einops.layers.torch import Rearrange
from torch import nn
def log(t, eps=1e-10):
return torch.log(t.clamp(min=eps))
def exists(val):
return val is not None
... | zeta-main | zeta/rl/reward_model.py |
import torch
from zeta.nn.attention.cross_attention import CrossAttend
from zeta.nn.architecture.transformer import Encoder
encoder = Encoder(dim=512, depth=6)
model = CrossAttend(dim=512, depth=6)
nodes = torch.randn(1, 1, 512)
node_mask = torch.ones(1, 1).bool()
neighbors = torch.randn(1, 5, 512)
neighbor_mask = ... | zeta-main | playground/cross_attend.py |
import torch
from zeta import FlashAttention
q = torch.randn(2, 4, 6, 8)
k = torch.randn(2, 4, 10, 8)
v = torch.randn(2, 4, 10, 8)
attention = FlashAttention(causal=False, dropout=0.1, flash=False)
output = attention(q, k, v)
print(output.shape) | zeta-main | playground/flash_attention.py |
import torch
from zeta.models import GPT4MultiModal
image = torch.randint(1, 3, 256, 256)
text = torch.randint(0, 20000, (1, 1024))
model = GPT4MultiModal()
output = model(text, image) | zeta-main | playground/models/gpt4_multimodal.py |
import torch
from zeta.models.gpt4 import GPT4
x = torch.randint(0, 256, (1, 1024)).cuda()
gpt4 = GPT4()
gpt4(x)
| zeta-main | playground/models/gpt4.py |
# Copyright (c) 2022 Agora
# Licensed under The MIT License [see LICENSE for details]
| zeta-main | tests/__init__.py |
from zeta import MultiheadAttention
import time
import unittest
import torch
from zeta import MultiheadAttention
class TestMultiheadAttention(unittest.TestCase):
def test_output_shape(self):
# Setup
input_tensor = torch.randn(2, 128, 512)
dilated_attention = MultiheadAttention(512, 8, 2,... | zeta-main | tests/example.py |
from zeta.utils.attention.multihead_attention import MultiheadAttention
import torch
import unittest
from zeta import MultiheadAttention
class TestMultiheadAttention(unittest.TestCase):
def setUp(self):
self.args = {
'xpos_rel_pos': True,
'xpos_scale_base': 2,
'layernor... | zeta-main | tests/test_mha.py |
import logging
import os
from functools import partial
from math import ceil
from timeit import Timer
from typing import Callable, List, NamedTuple
import plotly.graph_objects as go
import torch
from zeta.nn.attention.dilated_attention import DilatedAttention
# Generic benchmarking parameters
BATCH_SIZE = 1
TOTAL_TO... | zeta-main | benchmarks/dilated_bench.py |
import torch
from gpt3.gpt3 import GPT3
x = torch.randint(0, 256, (1, 1024)).cuda()
model = GPT3()
model(x) | GPT3-main | example.py |
from torch import nn
# from gpt3.model import Transformer, Decoder, AutoregressiveWrapper
from zeta import Transformer, Decoder, AutoregressiveWrapper
class GPT3(nn.Module):
def __init__(
self,
num_tokens=50477,
max_seq_len=4096,
dim=12288,
depth=96,
... | GPT3-main | gpt3/gpt3.py |
from gpt3.gpt3 import GPT3
from gpt3.train import train | GPT3-main | gpt3/__init__.py |
import math
import multiprocessing
import os
from datetime import timedelta
from functools import partial
from itertools import chain
import torch
########### SETUP CONFIG
import torch.distributed as dist
from accelerate import Accelerator
from accelerate.logging import get_logger
from accelerate.state import Acceler... | GPT3-main | gpt3/train.py |
CELESTIAL-1-master | cstx/__init__.py | |
import copy
from inspect import isfunction
from typing import List
import tqdm
import torch
import torch.nn as nn
import numpy as np
from functools import partial
from contextlib import contextmanager
from research.BindDiffusion.ldm.modules.diffusionmodules.util import noise_like
#HELPERS
def exists(val):
return... | CELESTIAL-1-master | cstx/model.py |
from setuptools import setup, find_packages
setup(
name = 'AttentionGrid',
packages = find_packages(exclude=['examples']),
version = '0.0.2',
license='APACHE',
description = 'AttentionGrid - Library',
author = 'Phil Wang',
author_email = 'kye@apac.ai',
url = 'https://github.com/kyegomez/AttentionGrid',... | AttentionGrid-main | setup.py |
AttentionGrid-main | AttentionGrid/__init__.py | |
from abc import ABC, abstractmethod
class AbstractAttention(ABC):
@abstractmethod
def forward(self, *args, **kwargs):
""" Perform the forward pass of the attention mechanism. """
pass
class AbstractEncoder(ABC):
@abstractmethod
def forward(self, *args, **kwargs):
""" Perform th... | AttentionGrid-main | AttentionGrid/abstract/abstract.py |
AttentionGrid-main | AttentionGrid/abstract/__init__.py | |
import math
import numpy as np
import torch
import torch.nn as nn
from fairscale.nn import checkpoint_wrapper, wrap
from torchscale.architecture.utils import init_bert_params
from torchscale.component.droppath import DropPath
from torchscale.component.feedforward_network import FeedForwardNetwork, make_experts
from t... | AttentionGrid-main | AttentionGrid/core/decoder.py |
class Encoder(AttentionLayers):
def __init__(self, **kwargs):
assert 'causal' not in kwargs, 'cannot set causality on encoder'
super().__init__(causal = False, **kwargs)
class Decoder(AttentionLayers):
def __init__(self, **kwargs):
assert 'causal' not in kwargs, 'cannot set causality... | AttentionGrid-main | AttentionGrid/core/transformer_wrapper.py |
import math
import torch
import torch.nn.functional as F
from torch import nn, Tensor
try:
from apex.normalization import FusedLayerNorm as LayerNorm
except ModuleNotFoundError:
from torch.nn import LayerNorm
# from .multiway_network import MultiwayWrapper
# from .xpos_relative_position import XPOS
from ... | AttentionGrid-main | AttentionGrid/attentions/torchscale_multihead/torchscale_multihead.py |
AttentionGrid-main | AttentionGrid/attentions/torchscale_multihead/__init__.py | |
AttentionGrid-main | AttentionGrid/attentions/landmark_attention/__init__.py | |
import math
import triton
import torch
import triton.language as tl
@triton.jit
def _fwd_kernel(#debug, sdz, sdh, sdm, sdn,
Q, K, V, sm_scale,
Out,
sqz, sqh, sqm, sqd, # shape = (Z,H,N_CTX_Q,D)
skz, skh, skn, skd, # shape = (Z,H,N_CTX_KV,D)
svz, svh, svn, svd, # shape = (Z,H,N_CTX_KV,D)
soz, s... | AttentionGrid-main | AttentionGrid/attentions/landmark_attention/fused_landmark_attention.py |
AttentionGrid-main | AttentionGrid/attentions/dynamic_sparse_flash_attention/__Init__.py | |
import math
import torch
import triton
import triton.language as tl
@triton.jit
def _fwd_kernel_hash(
Q, K, V, sm_scale,
Out,
sqz, sqh, sqm, sqd, # shape = (Z,H,N_CTX_Q,D)
skz, skh, skn, skd, # shape = (Z,H,N_CTX_KV,D)
svz, svh, svn, svd, # shape = (Z,H,N_CTX_KV,D)
soz, soh, som, sod, # shape ... | AttentionGrid-main | AttentionGrid/attentions/dynamic_sparse_flash_attention/dynamic_sparse_triton.py |
import torch
import torch.nn as nn
from einops import rearrange
from flash_attn.flash_attn_interface import flash_attn_unpadded_qkvpacked_func
from flash_attn.bert_padding import unpad_input, pad_input
class FlashAttention(nn.Module):
"""Implement the scaled dot product attention with softmax.
Arguments
... | AttentionGrid-main | AttentionGrid/attentions/stacked_flash_attention/attention.py |
AttentionGrid-main | AttentionGrid/attentions/stacked_flash_attention/__init__.py | |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
import math
import torch.nn.functional as F
def pad_at_dim(t, pad, dim=-1, value=0.):
dims_from_right = (- dim - 1) if dim < 0 ... | AttentionGrid-main | AttentionGrid/attentions/stacked_flash_attention/utils/embeddings.py |
#add ability to choose your own tokenizer, and embedder, and ask what else can be done for production level training
import math
from random import random
import torch
from torch import nn, einsum, Tensor
import torch.nn.functional as F
from functools import partial, wraps
from inspect import isfunction
from collec... | AttentionGrid-main | AttentionGrid/attentions/x_transformers_attention/x_transformers.py |
AttentionGrid-main | AttentionGrid/attentions/x_transformers_attention/__Init__.py | |
import functools
from functools import partial
from typing import NamedTuple, Optional
import flax.linen as nn
import jax
import jax.numpy as jnp
import numpy as np
from einops import rearrange
from flax.linen import combine_masks
from jax import lax
from jax import numpy as jnp
from abstract import AbstractAttention... | AttentionGrid-main | AttentionGrid/attentions/blockwise_parallel/blockwise_attention_jax.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from functools import partial
def quick_gelu(x):
return x * torch.sigmoid(1.702 * x)
ACT2FN = {
"gelu": F.gelu,
"relu": F.relu,
"silu": F.silu,
"swish": F.swish,
"gelu_new": quick_gelu,
"quick_gelu": q... | AttentionGrid-main | AttentionGrid/attentions/blockwise_parallel/blockwise_attention_torch.py |
import torch
from blockwise_attention_torch import BlockwiseParallel
#constants
MASK_VALUE = -1e10
batch_size= 8
sequence_length = 8192
hidden_size = 256
num_heads = 8
rotary_dim = 64
intermediate_size = 512
#random tensor
input_tensor = torch.randn(batch_size, sequence_length, hidden_size)
#create position_ids
... | AttentionGrid-main | AttentionGrid/attentions/blockwise_parallel/test.py |
AttentionGrid-main | AttentionGrid/attentions/dilation_attention/__init__.py | |
import torch
import torch.nn as nn
from flash_attn.flash_attention import FlashMHA
# Replace this with your correct GPU device
device = "cuda:0"
dtype=torch.float16
class DilatedAttention(nn.Module):
def __init__(self, d_model, num_heads, dilation_rate, segment_size, dropout=0.0):
super(DilatedAttention,... | AttentionGrid-main | AttentionGrid/attentions/dilation_attention/main.py |
import torch
from AttentionGrid import fused_landmark_attention
# Define some input data
q = torch.randn(64, 12, 64)
k = torch.randn(64, 12, 64)
v = torch.randn(64, 12, 64)
is_mem = torch.randn(64, 12, 64)
# You can now use the fused landmark attention function in your code
output = fused_landmark_attention(q, k, v,... | AttentionGrid-main | examples/landmark_triton.py |
from AttentionGrid import BlockwiseParallel
import torch
# Initialize the class
bp = BlockwiseParallel(
hidden_size=768,
num_heads=12,
rotary_dim=32,
intermediate_size=3072
)
# Suppose we have hidden_states, attention_mask, and position_ids as input data
hidden_states = torch.rand(1, 100, 768)
posi... | AttentionGrid-main | examples/blockwise_torch.py |
from AttentionGrid import BlockwiseParallelJax
import jax.numpy as jnp
# Initialize the class
bpjax = BlockwiseParallelJax(
q_chunk_size=64,
k_chunk_size=64,
hidden_size=768,
num_heads=12,
rotary_dim=32,
intermediate_size=3072
)
# Suppose we have hidden_states, attention_mask, and positio... | AttentionGrid-main | examples/blockwise_jax.py |
from AttentionGrid import sparse_attn
# Define some hyperparameters
BATCH = 64
H = 12
n_ctx = 100
D_HEAD = 64
# You can now use the sparse attention function in your code
output = sparse_attn(num_buckets_or_sparsity=128, n_ctx=n_ctx, mode='fwd')
| AttentionGrid-main | examples/dynamic_sparse_attention_triton.py |
Gen1-main | gen1/__init__.py | |
Gen1-main | gen1/model.py | |
from collections import namedtuple
from dataclasses import dataclass
from functools import partial, wraps
from typing import Optional
import torch
import torch.nn.functional as F
from einops import rearrange, repeat
from packaging import version
from torch import Tensor, einsum, nn
# constants
EfficientAttentionConf... | Gen1-main | gen1/attend.py |
import os
import requests
from requests.exceptions import RequestException
import time
from libgen_api import LibgenSearch
import zipfile
import threading
from ebooklib import epub
from PyPDF2 import PdfReader
# from pdfminer.high_level import extract_text
from bs4 import BeautifulSoup
import json
import gzip
def sea... | all-books-on-libgen-master | libgen_api/harvest2.py |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="libgen_api",
packages=["libgen_api"],
version="1.0.0",
description="Search Library genesis by Title or Author",
long_description_content_type="text/markdown",
long_description=long_des... | all-books-on-libgen-master | libgen_api/setup.py |
#example
#download books -> analyze them -> organize in a structured format[title, authors, content, metadata, published] -> each book with all data formats => json
import os
import requests
from requests.exceptions import RequestException
import time
from libgen_api import LibgenSearch
import zipfile
from ebooklib imp... | all-books-on-libgen-master | libgen_api/harvest.py |
import pytest
from libgen_api.libgen_search import LibgenSearch
title = "Pride and Prejudice"
author = "Agatha Christie"
ls = LibgenSearch()
class TestBasicSearching:
def test_title_search(self):
titles = ls.search_title(title)
first_result = titles[0]
assert title in first_result["Titl... | all-books-on-libgen-master | libgen_api/test/test_pytest.py |
"""
Basic testing script for libgen-api.
Runs through a number of searches using different parameters, outputs results to terminal.
Run -
python3 test.py
"""
from libgen_api.libgen_search import LibgenSearch
import json
title = "Pride and Prejudice"
author = "Agatha Christie"
# helper function to print first ti... | all-books-on-libgen-master | libgen_api/test/manualtesting.py |
from .search_request import SearchRequest
import requests
from bs4 import BeautifulSoup
MIRROR_SOURCES = ["GET", "Cloudflare", "IPFS.io", "Infura"]
class LibgenSearch:
def search_title(self, query):
search_request = SearchRequest(query, search_type="title")
return search_request.aggregate_request... | all-books-on-libgen-master | libgen_api/libgen_api/libgen_search.py |
all-books-on-libgen-master | libgen_api/libgen_api/libgen_api_helpers.py | |
from .search_request import SearchRequest
from .libgen_search import LibgenSearch
| all-books-on-libgen-master | libgen_api/libgen_api/__init__.py |
import requests
from bs4 import BeautifulSoup
# WHY
# The SearchRequest module contains all the internal logic for the library.
#
# This encapsulates the logic,
# ensuring users can work at a higher level of abstraction.
# USAGE
# req = search_request.SearchRequest("[QUERY]", search_type="[title]")
class SearchRequ... | all-books-on-libgen-master | libgen_api/libgen_api/search_request.py |
from setuptools import setup, find_packages
setup(
name = 'tree-of-thoughts',
packages = find_packages(exclude=[]),
version = '0.3.6',
license='MIT',
description = 'Tree of Thoughts - Pytorch',
author = 'Kye Gomez',
author_email = 'kye@apac.ai',
long_description_content_type = 'text/markdown',
url = ... | tree-of-thoughts-main | setup.py |
import os
from tree_of_thoughts.models.openai_models import OpenAILanguageModel
from tree_of_thoughts.treeofthoughts import MonteCarloTreeofThoughts
api_model= "gpt-3.5-turbo"
api_key = os.getenv("OPENAI_API_KEY")
model = OpenAILanguageModel(api_key=api_key, api_model=api_model)
# Initialize the MonteCarloTreeofTh... | tree-of-thoughts-main | example.py |
from abc import ABC, abstractmethod
import openai
class AbstractLanguageModel(ABC):
@abstractmethod
def generate_thoughts(self, state, k):
pass
@abstractmethod
def evaluate_states(self, states):
pass
class CustomLanguageModel(AbstractLanguageModel):
def __init__(self, model):
... | tree-of-thoughts-main | experiements/treeofthoughts-v1.py |
import concurrent.futures
from abc import ABC, abstractmethod
import openai
class AbstractLanguageModel(ABC):
@abstractmethod
def generate_thoughts(self, state, k):
pass
@abstractmethod
def evaluate_states(self, states):
pass
class CustomLanguageModel(AbstractLanguageModel):
def ... | tree-of-thoughts-main | experiements/hyperoptimized.py |
import os
import json
import itertools
import argparse
import numpy as np
from functools import partial
from models import gpt, gpt_usage
from tasks import get_task
class CustomLanguageModel:
def __init__(self, model):
self.model = model
def generate_thoughts(self, state, k):
# Implement the t... | tree-of-thoughts-main | experiements/treeofthoughtsv2.py |
import concurrent.futures
from abc import ABC, abstractmethod
import openai
import os
import guidance
import time
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers import pipeline
import json
DATA_PATH = './data'
class AbstractLanguageModel(ABC):
@abstractmethod
def generate_tho... | tree-of-thoughts-main | experiements/latest.py |
class TreeofThoughts:
def __init__(self, model, search_algorithm):
self.model = model
self.search_algorithm = search_algorithm
def solve(self, x, k, T, b, vth):
if self.search_algorithm == 'BFS':
return self.tot_bfs(x, k, T, b)
elif self.search_algorithm == 'DF... | tree-of-thoughts-main | experiements/first.py |
import concurrent.futures
from abc import ABC, abstractmethod
import openai
import os
import guidance
import time
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers import pipeline
import json
DATA_PATH = './data'
import logging
import argparse
from dotenv import load_dotenv
load_dotenv(... | tree-of-thoughts-main | experiements/main.py |
from abc import ABC, abstractmethod
import openai
class AbstractLanguageModel(ABC):
@abstractmethod
def generate_thoughts(self, state, k):
pass
@abstractmethod
def evaluate_states(self, states):
pass
class CustomLanguageModel(AbstractLanguageModel):
def __init__(self, model):
... | tree-of-thoughts-main | experiements/v2.py |
import os
import time
import json
DATA_PATH = './data'
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
DATA_PATH = './data'
class TreeofThoughts:
def __init__(self, model, search_algorithm):
self.model = mode... | tree-of-thoughts-main | experiements/optimized.py |
from abc import ABC, abstractmethod
import openai
class AbstractLanguageModel(ABC):
@abstractmethod
def generate_thoughts(self, state, k):
pass
@abstractmethod
def evaluate_states(self, states):
pass
class CustomLanguageModel(AbstractLanguageModel):
def __init__(self, model):
... | tree-of-thoughts-main | experiements/old-main/treeofthoughts.py |
from abc import ABC, abstractmethod
import openai
class AbstractLanguageModel(ABC):
@abstractmethod
def generate_thoughts(self, state, k):
pass
@abstractmethod
def evaluate_states(self, states):
pass
class CustomLanguageModel(AbstractLanguageModel):
def __init__(self, model):
... | tree-of-thoughts-main | experiements/old-main/treeofthoughts-v2.py |
import os
import json
import itertools
import argparse
import numpy as np
from functools import partial
from models import gpt, gpt_usage
from tasks import get_task
def get_value(task, x, y, n_evaluate_sample, cache_value=True):
value_prompt = task.value_prompt_wrap(x, y)
if cache_value and value_prompt in tas... | tree-of-thoughts-main | experiements/tree-of-thought-llm/run.py |
import openai
import backoff
completion_tokens = prompt_tokens = 0
@backoff.on_exception(backoff.expo, openai.error.OpenAIError)
def completions_with_backoff(**kwargs):
return openai.ChatCompletion.create(**kwargs)
def gpt(prompt, model="gpt-4", temperature=0.7, max_tokens=1000, n=1, stop=None) -> list:
mes... | tree-of-thoughts-main | experiements/tree-of-thought-llm/models.py |
def get_task(name, file=None):
if name == 'game24':
from .game24 import Game24Task
return Game24Task(file)
elif name == 'text':
from .text import TextTask
return TextTask(file)
elif name == 'crosswords':
from .crosswords import MiniCrosswordsTask
return MiniCr... | tree-of-thoughts-main | experiements/tree-of-thought-llm/tasks/__init__.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.