An open source code generation model trained on permissively licensed code and released by Replit. The V1.5, 3B variant is the basis for this implementation, and weights are obtained via Hugging Face. This pipeline demonstrates code completion from an initial prompt using Replit's Code V1.5 3B large language model. The model itself has been constructed from end to end in the Mojo language using the MAX Graph API.
Read the code and instructions, and run on desktop.
An open source code generation model trained on permissively licensed code and released by Replit. The V1.5, 3B variant is the basis for this implementation, and weights are obtained via Hugging Face. This pipeline demonstrates code completion from an initial prompt using Replit's Code V1.5 3B large language model. The model itself has been constructed from end to end in the Mojo language using the MAX Graph API.
Read the code and instructions, and run on desktop.
Language: Mojo 🔥
API: MAX Graph
This pipeline demonstrates code completion from an initial prompt using Replit's Code V1.5 3B large language model. The model itself has been constructed from end to end in the Mojo language using the MAX Graph API.
The MAX Graph API provides an accessible Mojo interface to the construction of flexible accelerated compute graphs, which are then optimized by the MAX Engine's advanced graph compiler. This pipeline showcases how a large language model can be fully defined using Mojo and MAX Graphs and then compiled for optimal inference performance via the MAX Engine.
Replit Code is an open source code generation model trained on permissively licensed code and released by Replit. The V1.5, 3B variant is the basis for this implementation, and weights are obtained via Hugging Face.
The easiest way to try out this pipeline is with our Magic command-line tool. Follow the instructions to install Magic. Once installed, you can try out code generation using Replit Code with the following command:
magic run replit --prompt 'def hello():\n print("hello world")'
On first execution, the tokenizer library and model weights will be
downloaded and placed in a .cache/modular
subdirectory within your home
directory. The model will then be compiled and text completion will begin from
the specified prompt.
To modify or build upon the pipeline code, you can use the following steps:
Install MAX:
If MAX is not already installed, follow the installation instructions to set it up on your system.
Clone the MAX examples repository:
If you don't already have a local clone of this repository, create one via:
git clone https://github.com/modularml/max.git
The following instructions assume that you're present within this pipeline's directory, and you can change to it after cloning:
cd max/examples/graph-api/pipelines/replit/
Install Python dependencies:
You'll need numpy and the Transformers library as we will be using its tokenizers. You can do this by running:
pip install numpy transformers
Run the code completion demo:
All of the pipelines have been configured to use a common driver, located in the directory hosting all MAX Graph examples. Assuming you're starting at the path of this README, the command invocation will look like:
mojo ../../run_pipeline.🔥 replit --prompt 'def hello():\n print("hello world")'
The following command-line options are available to customize operation of the pipeline:
--model-path
: Overrides the default model weights, and allows for an
already-downloaded pretrained weight file to be used with the model.--prompt
: The text prompt to use for further code generation.--max-length
: An optional token generation configuration to specify maximum
sequence length.--max-new-tokens
: An optional token generation configuration to specify
maximum number of tokens.--quantization-encoding
: The encoding to use for a datatype that can be
quantized to a low bits per weight format. The options for quantized formats
will download and cache default weights.--warmup-pipeline
: Performs a warmup run of the pipeline before text
generation.This isn't an exhaustive list, but here are some ideas for ways in which this pipeline may be extended or improved:
transformers
library via Python
interoperability and it might be useful to have this all in Mojo.425 lines - 14.5 KB
Graph
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2024, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from pathlib import cwd, Path
from collections import Dict, Optional
import sys
from os import setenv
from max.engine import InferenceSession, Model
from max.graph.quantization import (
BFloat16Encoding,
Float32Encoding,
QuantizationEncoding,
)
from max.tensor import TensorSpec, TensorShape
from max.driver import (
Device,
Tensor,
AnyTensor,
cpu_device,
AnyMemory,
)
from max.driver._cuda import cuda_device
from pipelines.weights.gguf import GGUFFile
from .config import (
ReplitConfigRegistry,
get_replit_base_default_config,
get_replit_model_url,
)
from .model.replit import Replit
from .weights.hyperparams import get_default
from ..configs.registry import ConfigRegistry, ConfigRegistryDict
from ..configs.parse_args import (
OptionValue,
parse_args,
register_pipeline_configs,
)
from ..samplers.token_sampler import TokenSampler
from ..samplers.weighted_sampler import WeightedSampler
from ..tokenizer import AutoTokenizer
from ..llama3.metrics import Metrics
from ..weights.download import download_to_cache
alias DEFAULT_MAX_SEQ_LEN = 512
@value
struct Config:
var config: Dict[String, OptionValue]
var dtype: DType
def __init__(
inout self,
additional_pipeline_args: Optional[ConfigRegistryDict] = None,
additional_defaults: Optional[Dict[String, OptionValue]] = None,
):
config_registry = ReplitConfigRegistry(additional_pipeline_args)
default_configs = get_replit_base_default_config()
if additional_defaults:
default_configs.update(additional_defaults.value())
self.config = register_pipeline_configs(
config_registry.registry,
parse_args(),
default_configs,
)
# Finalize parsed arguments.
self.dtype = DType.float32
_raw_type = self.config["quantization-encoding"]
raw_type = _raw_type[String]
if not sys.info.is_x86() and raw_type == "bfloat16":
raise "bfloat16 is not supported for ARM architectures."
if raw_type == "float32":
self.dtype = DType.float32
elif raw_type == "bfloat16":
self.dtype = DType.bfloat16
else:
raise "quantization-encoding must be 'bfloat16' or 'float32', got" + raw_type
_model_path = self.config["model-path"]
model_path = _model_path[Path]
if not model_path:
model_path = download_to_cache(get_replit_model_url(raw_type))
print("Using checkpoint at", model_path)
self.config["model-path"] = model_path
if not model_path.exists():
raise ("Unable to find checkpoint at " + str(model_path))
def __contains__(self, key: String):
return key in self.config
fn get(inout self, key: String) raises -> OptionValue:
"""Returns an option value for `key` in the underlying config.
Args:
key: Key for the underlying config option.
Returns:
An OptionValue.
Raises:
An error for invalid key.
"""
try:
return self.config[key]
except:
raise "KeyError: " + key
fn set(inout self, key: String, val: OptionValue):
"""Sets a new value for a given config key. This will overwrite the old
value if the key is already present.
Args:
key: A string based key for the underlying config option.
val: A new value for a key that already exist.
"""
self.config[key] = val
struct ReplitPipeline[dtype: DType]:
"""Code completion model based on Replit.
Parameters:
dtype: The DType of the weights and inputs to this model.
"""
var _replit: Replit[GGUFFile, dtype]
"""Class that builds the Replit model graph."""
var _device: Device
"""Chosen device for execution."""
var _run_on_gpu: Bool
"""Device chosen is gpu or not."""
var _cpu_device: Device
"""An instance of cpu device. If chosen device is cpu this will
be a copy of chosen device."""
var _session: InferenceSession
"""MAX Engine session that holds and runs the model."""
var _model: Model
"""Model compiled, initialized and ready for execution."""
var _tokenizer: AutoTokenizer
"""Tokenizer for encoding/decoding the inputs and outputs."""
# Token generation settings.
var _max_length: Optional[Int]
var _max_new_tokens: Optional[Int]
# Attributes updated during generation.
var _initial_prompt: String
"""Initial prompt user passed to `ReplitPipeline.reset()` method."""
var _max_seq_len: Int
"""Maximum sequence length that will be generated by next_token(). This
value includes the length of the inital prompt."""
var _k_cache: AnyMemory
"""Cache containing past computed attention keys."""
var _v_cache: AnyMemory
"""Cache containing past computed attention values."""
var _next_token_tensor: AnyMemory
"""ID of the last token generated by `ReplitPipeline.next_token()`, which
will be used as the next input to the model."""
var _cur_seq_len: Int
"""Length of the current sequence (including prompt)."""
var _is_end_of_text: Bool
"""Whether text generation has reached an end-of-text token."""
def __init__(
inout self,
model_path: Path,
use_gpu: Bool = False,
max_length: Optional[Int] = None,
max_new_tokens: Optional[Int] = None,
experimental_load_graph: String = "",
experimental_store_graph: String = "",
):
"""Builds and compiles a Replit model to get ready for execution."""
# Generate a graph that does a single forward pass of the replit model.
print("Building model...")
self._replit = Replit[GGUFFile, dtype](get_default())
self._device = cuda_device() if use_gpu else cpu_device()
self._run_on_gpu = use_gpu
# TODO(field sensitive lifetimes): Remove tmp_device.
var tmp_device = cpu_device() if use_gpu else self._device
self._cpu_device = tmp_device^
self._session = InferenceSession(self._device)
# Compile and load the graph, which generates the MLIR and runs
# optimization passes on it.
print("Compiling...")
if experimental_load_graph != "":
self._model = self._session.load(experimental_load_graph)
else:
model = GGUFFile(model_path)
g = self._replit.build_graph(
model,
"replit",
with_attention_mask=True,
use_cache=True,
)
self._model = self._session.load(g)
if experimental_store_graph:
self._model.export_compiled_model(experimental_store_graph)
# Set up tokenizer.
var hf_model_name = "replit/replit-code-v1_5-3b"
self._tokenizer = AutoTokenizer(hf_model_name)
# Set default token generation options.
self._max_length = None
if max_length:
self._max_length = max_length.value()
self._max_new_tokens = None
if max_new_tokens:
self._max_new_tokens = max_new_tokens.value()
# Initialize token generation attributes.
self._initial_prompt = ""
self._max_seq_len = 0
kv_cache = self._replit.create_empty_cache(self._device)
self._k_cache = kv_cache[0].take()
self._v_cache = kv_cache[1].take()
self._next_token_tensor = AnyTensor()
self._cur_seq_len = 0
self._is_end_of_text = True
def _get_max_tokens(self, prompt_len: Int) -> Int:
"""Returns the max sequence length to generate (including the prompt).
"""
if self._max_length:
if self._max_new_tokens:
return min(
self._max_new_tokens.value() + prompt_len,
self._max_length.value(),
)
else:
return self._max_length.value()
elif self._max_new_tokens:
return self._max_new_tokens.value() + prompt_len
else:
return DEFAULT_MAX_SEQ_LEN
def reset(inout self, prompt: String) -> Int:
"""Resets the prompt and model state."""
self._initial_prompt = prompt
self._max_seq_len = self._get_max_tokens(len(prompt))
kv_cache = self._replit.create_empty_cache(self._device)
self._k_cache = kv_cache[0].take()
self._v_cache = kv_cache[1].take()
encoded_prompt = self._tokenizer.encode(List(prompt))
next_token_tensor = Tensor[DType.int64, 2](
TensorShape(1, len(encoded_prompt)), self._cpu_device
)
for i in range(len(encoded_prompt)):
next_token_tensor[0, i] = encoded_prompt[i]
self._set_next_token_tensor(next_token_tensor)
self._cur_seq_len = len(encoded_prompt)
self._max_seq_len = self._get_max_tokens(self._cur_seq_len)
self._is_end_of_text = False
return encoded_prompt.size
def next_token(inout self) -> Optional[String]:
"""Generates the next token, or None if the end has been reached."""
return self.next_token(WeightedSampler(0))
def _set_next_token_tensor(inout self, owned next_token_tensor: AnyTensor):
"""Set the given value as next token tensor. If the chosen
device is gpu, value will be copied over to the device."""
self._next_token_tensor = next_token_tensor^
def _get_attention_mask(self) -> AnyTensor:
"""Generates attention mask for current input sequence.
Result is placed on the chosen device.
"""
attention_mask_tensor = Tensor[DType.bool, 2](
TensorShape(1, self._cur_seq_len), self._cpu_device
)
for i in range(self._cur_seq_len):
attention_mask_tensor[0, i] = True
return attention_mask_tensor
def next_token[
Sampler: TokenSampler
](inout self, sampler: Sampler) -> Optional[String]:
"""Generates the next token, or None if the end has been reached."""
if self._is_end_of_text or self._max_seq_len - self._cur_seq_len <= 0:
return None
results = self._model.execute(
self._next_token_tensor.take(),
self._get_attention_mask(),
self._k_cache.take(),
self._v_cache.take(),
)
output = results[0].take()
self._k_cache = results[1].take()
self._v_cache = results[2].take()
logits = output.to_device_tensor()
if self._run_on_gpu:
logits = logits.copy_to(self._cpu_device)
var token: Int64 = sampler.sample(logits.to_tensor[dtype, 2]()).selected
if self._tokenizer.is_end_of_text(token):
self._is_end_of_text = True
return None
self._cur_seq_len += 1
next_token_tensor = Tensor[DType.int64, 2](
TensorShape(1, 1), self._cpu_device
)
next_token_tensor[0, 0] = token
self._set_next_token_tensor(next_token_tensor)
return self._tokenizer.decode(token)
def dispatch[dtype: DType](config: Config):
"""Dispatches token generation for a model."""
metrics = Metrics()
metrics.begin_timing_startup()
# Set up the Replit model prepare it for token generation.
var max_length: Optional[Int] = None
if "max-length" in config:
max_length = config.get("max-length")[Int]
var max_new_tokens: Optional[Int] = None
if "max-new-tokens" in config:
max_new_tokens = config.get("max-new-tokens")[Int]
replit = ReplitPipeline[dtype](
config.get("model-path")[Path],
use_gpu=config.get("experimental-use-gpu")[Bool],
max_length=max_length,
max_new_tokens=max_new_tokens,
experimental_load_graph=config.get("experimental-load-graph")[String],
experimental_store_graph=config.get("experimental-store-graph")[String],
)
metrics.end_timing_startup()
input_string = config.get("prompt")[String]
print("Running on input:", input_string)
# Make sure newlines are properly encoded in the prompt.
prompt = input_string.replace("\\n", "\n")
# Run code generation.
metrics.begin_timing_prompt()
sampler = WeightedSampler(
config.get("temperature")[Float64].cast[DType.float32](),
config.get("min-p")[Float64].cast[DType.float32](),
)
# If a pipeline warmup is needed, run a single token completion after the
# prompt, get a token after that, and reset.
if config.get("warmup-pipeline")[Bool]:
print("Warming up pipeline...")
metrics.begin_timing_warmup()
_ = replit.reset(prompt)
_ = replit.next_token(sampler)
_ = replit.next_token(sampler)
metrics.end_timing_warmup()
tokens_in_prompt = replit.reset(prompt)
metrics.set_tokens_in_prompt(tokens_in_prompt)
print("Output:")
metrics.begin_timing_generation()
while True:
s = replit.next_token(sampler)
if not s:
break
metrics.new_token()
print(s.value(), end="")
metrics.end_timing()
print()
metrics.print()
# Avoid destroying heavyweight objects inside the timing loop.
_ = sampler^
_ = replit^
def replit_run():
config = Config()
@parameter
if not sys.info.is_x86():
dispatch[DType.float32](config)
else:
encoding = config.get("quantization-encoding")[String]
if encoding == BFloat16Encoding.id():
dispatch[DType.bfloat16](config)
elif encoding == Float32Encoding.id():
dispatch[DType.float32](config)
else:
raise "--quantization-encoding must be 'bfloat16' or 'float32', got" + encoding
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
---- LLVM Exceptions to the Apache 2.0 License ----
As an exception, if, as a result of your compiling your source code, portions of this Software are embedded into an Object form of such source code, you may redistribute such embedded portions in such Object form without complying with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
In addition, if you combine or link compiled forms of this Software with software that is licensed under the GPLv2 ("Combined Software") and if a court of competent jurisdiction determines that the patent provision (Section 3), the indemnity provision (Section 9) or other Section of the License conflicts with the conditions of the GPLv2, you may retroactively and prospectively choose to deem waived or otherwise exclude such Section(s) of the License, but only in their entirety and only with respect to the Combined Software.
The LLVM Project contains third party software which is under different license terms. All such code will be identified clearly using at least one of two mechanisms:
LICENSE.txt
or
LICENSE
file at the top containing the specific license and restrictions
which apply to that software, or@ Copyright - Modular Inc - 2024