before_code
stringlengths
30
149k
reviewer_comment
stringlengths
16
20.6k
after_code
stringlengths
30
163k
diff_context
stringlengths
0
22.4k
file_path
stringlengths
6
155
comment_line
int64
0
26
language
stringclasses
19 values
quality_score
float64
0.07
1
comment_type
stringclasses
9 values
comment_length
int64
16
20.6k
before_lines
int64
2
4.61k
after_lines
int64
2
4.4k
is_negative
bool
2 classes
pr_title
stringlengths
7
140
pr_number
int64
18
61.2k
repo_name
stringclasses
29 values
repo_stars
int64
321
56k
repo_language
stringclasses
14 values
reviewer_username
stringclasses
378 values
author_username
stringclasses
739 values
user
stringlengths
361
200k
assistant
stringlengths
16
20.6k
system
stringclasses
1 value
import axios, { AxiosRequestConfig } from "axios"; import type { JWT } from "next-auth/jwt"; import { ChatItem, InferenceMessage, InferencePostMessageResponse } from "src/types/Chat"; import type { Readable } from "stream"; export class OasstInferenceClient { // this is not a long lived class, this is why the token ...
NEXT_PUBLIC_INFERENCE_SERVER_HOST will be undefined in production. We need to pass it from getServerSideProps. Or we can use getInitialProps in the `_app.tsx` file and pass it to a context or any global variable.
import axios, { AxiosRequestConfig } from "axios"; import { JWT } from "next-auth/jwt"; import { ChatItem, InferenceMessage, InferencePostMessageResponse, ModelInfo, WorkParametersInput, } from "src/types/Chat"; import type { Readable } from "stream"; export class OasstInferenceClient { // this is not a lo...
@@ -1,69 +1,38 @@ -/* eslint-disable @typescript-eslint/no-explicit-any */ import axios, { AxiosRequestConfig } from "axios"; -import Cookies from "cookies"; -import type { NextApiRequest, NextApiResponse } from "next"; -import { JWT } from "next-auth/jwt"; -import { ChatItem, InferenceTokenResponse, InferenceMessage,...
website/src/lib/oasst_inference_client.ts
11
TypeScript
0.786
suggestion
212
36
36
false
Login to inference through website
2,176
LAION-AI/Open-Assistant
29,137
Python
notmd
AbdBarho
Review this pull request change. Language: TypeScript File: website/src/lib/oasst_inference_client.ts PR Title: Login to inference through website BEFORE CODE: import axios, { AxiosRequestConfig } from "axios"; import type { JWT } from "next-auth/jwt"; import { ChatItem, InferenceMessage, InferencePostMessageRespon...
NEXT_PUBLIC_INFERENCE_SERVER_HOST will be undefined in production. We need to pass it from getServerSideProps. Or we can use getInitialProps in the `_app.tsx` file and pass it to a context or any global variable.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
self, pooling: Literal["mean", "last"] = "last", **kwargs, ): super().__init__(**kwargs) self.pooling = pooling or "last" @dataclass class GPTNeoXRewardModelOutput(ModelOutput): """ Reward model output. Args: logits (`torch.FloatTensor` of shape `(batch...
I personally prefer `isinstance(config, GPTNeoXConfig)`
self, pooling: Literal["mean", "last"] = "last", **kwargs, ): super().__init__(**kwargs) self.pooling = pooling or "last" @dataclass class GPTNeoXRewardModelOutput(ModelOutput): """ Reward model output. Args: logits (`torch.FloatTensor` of shape `(batch...
@@ -1,68 +1,94 @@ -import os -from typing import Literal, Optional, Union +from dataclasses import dataclass +from typing import Literal, Optional +import torch import torch.nn as nn -from models import get_specific_model -from transformers import PretrainedConfig, PreTrainedModel +from transformers import AutoConfi...
model/model_training/models/reward_model.py
26
Python
0.429
suggestion
55
51
51
false
Add GPTNeoXRewardModel
2,182
LAION-AI/Open-Assistant
29,137
Python
dvruette
andreaskoepf
Review this pull request change. Language: Python File: model/model_training/models/reward_model.py PR Title: Add GPTNeoXRewardModel BEFORE CODE: self, pooling: Literal["mean", "last"] = "last", **kwargs, ): super().__init__(**kwargs) self.pooling = pooling or "last" @d...
I personally prefer `isinstance(config, GPTNeoXConfig)`
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import transformers import utils import websocket import work from loguru import logger from oasst_shared import model_configs from oasst_shared.schemas import inference from settings import settings def terminate_worker(signum, frame): logger.warning(f"Signal {signum}. Terminating worker...") sys.exit(0) d...
Minor but we could avoid the nesting here
import transformers import utils import websocket import work from loguru import logger from oasst_shared import model_configs from oasst_shared.schemas import inference from settings import settings def terminate_worker(signum, frame): logger.warning(f"Signal {signum}. Terminating worker...") sys.exit(0) d...
@@ -23,19 +24,37 @@ def main(): signal.signal(signal.SIGINT, terminate_worker) logger.info(f"Inference protocol version: {inference.INFERENCE_PROTOCOL_VERSION}") - if settings.model_id != "_lorem": - if "llama" in settings.model_id: - tokenizer: transformers.PreTrainedTokenizer = transf...
inference/worker/__main__.py
26
Python
0.143
nitpick
41
51
51
false
Introduce model configs to abstract pairings of models and hardware
2,194
LAION-AI/Open-Assistant
29,137
Python
olliestanley
yk
Review this pull request change. Language: Python File: inference/worker/__main__.py PR Title: Introduce model configs to abstract pairings of models and hardware BEFORE CODE: import transformers import utils import websocket import work from loguru import logger from oasst_shared import model_configs from oasst_sh...
Minor but we could avoid the nesting here
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import utils import websocket import work from loguru import logger from oasst_shared import model_configs from oasst_shared.schemas import inference from settings import settings def terminate_worker(signum, frame): logger.warning(f"Signal {signum}. Terminating worker...") sys.exit(0) def main(): signa...
is this special handling still necessary with latest transformers version? (e.g. maybe wee need to update our json config files?)
import utils import websocket import work from loguru import logger from oasst_shared import model_configs from oasst_shared.schemas import inference from settings import settings def terminate_worker(signum, frame): logger.warning(f"Signal {signum}. Terminating worker...") sys.exit(0) def main(): signa...
@@ -23,19 +24,37 @@ def main(): signal.signal(signal.SIGINT, terminate_worker) logger.info(f"Inference protocol version: {inference.INFERENCE_PROTOCOL_VERSION}") - if settings.model_id != "_lorem": - if "llama" in settings.model_id: - tokenizer: transformers.PreTrainedTokenizer = transf...
inference/worker/__main__.py
26
Python
0.357
question
129
51
51
false
Introduce model configs to abstract pairings of models and hardware
2,194
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
yk
Review this pull request change. Language: Python File: inference/worker/__main__.py PR Title: Introduce model configs to abstract pairings of models and hardware BEFORE CODE: import utils import websocket import work from loguru import logger from oasst_shared import model_configs from oasst_shared.schemas import ...
is this special handling still necessary with latest transformers version? (e.g. maybe wee need to update our json config files?)
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import sys from oasst_shared import model_configs from settings import settings if __name__ == "__main__": model_config = model_configs.MODEL_CONFIGS.get(settings.model_config_name) if model_config is None: print(f"Unknown model config name: {settings.model_config_name}") sys.exit(2) prop ...
maybe add `len(sys.argv) > 1` check (since everything else is here handled gracefully)
import sys from oasst_shared import model_configs from settings import settings if __name__ == "__main__": model_config = model_configs.MODEL_CONFIGS.get(settings.model_config_name) if model_config is None: print(f"Unknown model config name: {settings.model_config_name}") sys.exit(2) if le...
@@ -0,0 +1,18 @@ +import sys + +from oasst_shared import model_configs +from settings import settings + +if __name__ == "__main__": + model_config = model_configs.MODEL_CONFIGS.get(settings.model_config_name) + if model_config is None: + print(f"Unknown model config name: {settings.model_config_name}") + ...
inference/worker/get_model_config_prop.py
14
Python
0.5
suggestion
86
19
22
false
Introduce model configs to abstract pairings of models and hardware
2,194
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
yk
Review this pull request change. Language: Python File: inference/worker/get_model_config_prop.py PR Title: Introduce model configs to abstract pairings of models and hardware BEFORE CODE: import sys from oasst_shared import model_configs from settings import settings if __name__ == "__main__": model_config =...
maybe add `len(sys.argv) > 1` check (since everything else is here handled gracefully)
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
const [messages, setMessages] = useState<InferenceMessage[]>([]); const [streamedResponse, setResponse] = useState<string | null>(null); const [queueInfo, setQueueInfo] = useState<QueueInfo | null>(null); const [isSending, setIsSending] = useBoolean(); useSWR<ChatItem>(API_ROUTES.GET_CHAT(chatId), get, { ...
Have you tested the top_k here? Andreas suggest an exponential function for this.
const [messages, setMessages] = useState<InferenceMessage[]>([]); const [streamedResponse, setResponse] = useState<string | null>(null); const [queueInfo, setQueueInfo] = useState<QueueInfo | null>(null); const [isSending, setIsSending] = useBoolean(); useSWR<ChatItem>(API_ROUTES.GET_CHAT(chatId), get, { ...
@@ -29,35 +35,34 @@ export const ChatConversation = ({ chatId }: ChatConversationProps) => { const [queueInfo, setQueueInfo] = useState<QueueInfo | null>(null); const [isSending, setIsSending] = useBoolean(); - useSWR<ChatItem>(API_ROUTES.GET_CHAT(chatId), get, { onSuccess: (chat) => setMessages(chat.messages)...
website/src/components/Chat/ChatConversation.tsx
26
TypeScript
0.214
question
81
51
51
false
Use new inference model config / API
2,208
LAION-AI/Open-Assistant
29,137
Python
notmd
AbdBarho
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatConversation.tsx PR Title: Use new inference model config / API BEFORE CODE: const [messages, setMessages] = useState<InferenceMessage[]>([]); const [streamedResponse, setResponse] = useState<string | null>(null); con...
Have you tested the top_k here? Andreas suggest an exponential function for this.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
class TokenResponse(WorkerResponseBase): response_type: Literal["token"] = "token" text: str log_prob: float | None token_id: int class GeneratedTextResponse(WorkerResponseBase): response_type: Literal["generated_text"] = "generated_text" text: str finish_reason: Literal["length", "eos_to...
this belongs to a PR stacked on top of this one
metrics: WorkerMetricsInfo | None = None class TokenResponse(WorkerResponseBase): response_type: Literal["token"] = "token" text: str log_prob: float | None token_id: int class GeneratedTextResponse(WorkerResponseBase): response_type: Literal["generated_text"] = "generated_text" text: st...
@@ -237,17 +239,18 @@ class InternalFinishedMessageResponse(WorkerResponseBase): class InternalErrorResponse(WorkerResponseBase): response_type: Literal["internal_error"] = "internal_error" error: str + message: MessageRead
oasst-shared/oasst_shared/schemas/inference.py
26
Python
0.071
suggestion
47
51
51
false
Create worker metrics manually for more control
2,229
LAION-AI/Open-Assistant
29,137
Python
yk
yk
Review this pull request change. Language: Python File: oasst-shared/oasst_shared/schemas/inference.py PR Title: Create worker metrics manually for more control BEFORE CODE: class TokenResponse(WorkerResponseBase): response_type: Literal["token"] = "token" text: str log_prob: float | None token_id:...
this belongs to a PR stacked on top of this one
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
await sendVote({ chat_id: chatId, message_id: messageId, score: newScore }); } catch { // TODO maybe we should trigger a toast or something // revert on any error setMessages((messages) => messages.map((message) => { return message.id !== messageId ? message :...
can you add a `useCallback` here?
await sendVote({ chat_id: chatId, message_id: messageId, score: newScore }); } catch { // TODO maybe we should trigger a toast or something // revert on any error setMessages((messages) => messages.map((message) => { return message.id !== messageId ? message :...
@@ -129,11 +185,13 @@ export const ChatConversation = ({ chatId }: ChatConversationProps) => { score={message.score} state={message.state} onVote={handleOnVote} + onRetry={() => handleOnRetry(message.parent_id!)}
website/src/components/Chat/ChatConversation.tsx
26
TypeScript
0.286
question
33
51
51
false
Enabling Threads and Retry for Web Chat
2,232
LAION-AI/Open-Assistant
29,137
Python
notmd
yk
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatConversation.tsx PR Title: Enabling Threads and Retry for Web Chat BEFORE CODE: await sendVote({ chat_id: chatId, message_id: messageId, score: newScore }); } catch { // TODO maybe we should trigger a t...
can you add a `useCallback` here?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
); const send = useCallback(async () => { const content = inputRef.current?.value.trim(); if (!content || !chatId) { return; } setIsSending.on(); // find last VALID assistant message const parent_id = currentThread .slice() .reverse() .find((m) => m.role...
```suggestion await initiate_assistant_message(prompter_message.id); ```
); const send = useCallback(async () => { const content = inputRef.current?.value.trim(); if (!content || !chatId) { return; } setIsSending.on(); // find last VALID assistant message const parent_id = currentThread .slice() .reverse() .find((m) => m.role...
@@ -48,53 +124,33 @@ export const ChatConversation = ({ chatId }: ChatConversationProps) => { // find last VALID assistant message const parent_id = - messages + currentThread .slice() .reverse() .find((m) => m.role === "assistant" && m.state === "complete")?.id ?? null;...
website/src/components/Chat/ChatConversation.tsx
26
TypeScript
0.571
suggestion
77
51
51
false
Enabling Threads and Retry for Web Chat
2,232
LAION-AI/Open-Assistant
29,137
Python
notmd
yk
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatConversation.tsx PR Title: Enabling Threads and Retry for Web Chat BEFORE CODE: ); const send = useCallback(async () => { const content = inputRef.current?.value.trim(); if (!content || !chatId) { return; ...
```suggestion await initiate_assistant_message(prompter_message.id); ```
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
raise fastapi.HTTPException(status_code=400, detail="Only assistant messages can be streamed.") if message.has_finished: raise fastapi.HTTPException(status_code=204, detail=message.state) async def event_generator(chat_id: str, message_id: str, worker_compat_hash: str | None): redis_cl...
could this be done in parallel like this? or is this a race condition? ```python [qdeq, qenq, mpos] = await asyncio.gather( work_queue.get_deq_counter(), work_queue.get_enq_counter(), queueing.get_pos_value(redis_client, message_id) ) ```
message: models.DbMessage = await ucr.get_message_by_id(chat_id=chat_id, message_id=message_id) if message.role != "assistant": raise fastapi.HTTPException(status_code=400, detail="Only assistant messages can be streamed.") if message.has_finished: raise fastapi.HTTPException(status_cod...
@@ -133,19 +134,33 @@ async def message_events( if message.has_finished: raise fastapi.HTTPException(status_code=204, detail=message.state) - async def event_generator(chat_id: str, message_id: str): + async def event_generator(chat_id: str, message_id: str, worker_compat_hash: str | None): ...
inference/server/oasst_inference_server/routes/chats.py
26
Python
1
bug
253
51
51
false
Computing message queue positions
2,235
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
yk
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/routes/chats.py PR Title: Computing message queue positions BEFORE CODE: raise fastapi.HTTPException(status_code=400, detail="Only assistant messages can be streamed.") if message.has_finished: raise...
could this be done in parallel like this? or is this a race condition? ```python [qdeq, qenq, mpos] = await asyncio.gather( work_queue.get_deq_counter(), work_queue.get_enq_counter(), queueing.get_pos_value(redis_client, message_id) ) ```
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
self.tokens.pop() yield from self.tokens else: yield from self.tokens def wait_for_inference_server(inference_server_url: str, timeout: int = 600): health_url = f"{inference_server_url}/health" time_limit = time.time() + timeout while True: try: ...
did not understand how this helps in computing message queue positions. is this needed ?
self.tokens.pop() yield from self.tokens else: yield from self.tokens def wait_for_inference_server(inference_server_url: str, timeout: int = 600): health_url = f"{inference_server_url}/health" time_limit = time.time() + timeout while True: try: ...
@@ -76,6 +76,7 @@ def wait_for_inference_server(inference_server_url: str, timeout: int = 600): def text_to_events(text: str, seed: int | None = None, pause: float = 0.0): + time.sleep(2)
inference/worker/utils.py
26
Python
0.214
question
88
51
51
false
Computing message queue positions
2,235
LAION-AI/Open-Assistant
29,137
Python
melvinebenezer
yk
Review this pull request change. Language: Python File: inference/worker/utils.py PR Title: Computing message queue positions BEFORE CODE: self.tokens.pop() yield from self.tokens else: yield from self.tokens def wait_for_inference_server(inference_server_url: str, ...
did not understand how this helps in computing message queue positions. is this needed ?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import redis.asyncio as redis from oasst_inference_server.settings import settings class RedisQueue: def __init__( self, redis_client: redis.Redis, queue_id: str, expire: int | None = None, with_counter: bool = False, counter_pos_expire: int = 1, ) -> None: ...
This is type hinted to return `None` but may not
import redis.asyncio as redis from oasst_inference_server.settings import settings class RedisQueue: def __init__( self, redis_client: redis.Redis, queue_id: str, expire: int | None = None, with_counter: bool = False, counter_pos_expire: int = 1, ) -> None: ...
@@ -3,36 +3,76 @@ class RedisQueue: - def __init__(self, redis_client: redis.Redis, queue_id: str) -> None: + def __init__( + self, + redis_client: redis.Redis, + queue_id: str, + expire: int | None = None, + with_counter: bool = False, + counter_pos_expire: int = 1,...
inference/server/oasst_inference_server/queueing.py
20
Python
0.357
suggestion
48
45
45
false
Computing message queue positions
2,235
LAION-AI/Open-Assistant
29,137
Python
olliestanley
yk
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/queueing.py PR Title: Computing message queue positions BEFORE CODE: import redis.asyncio as redis from oasst_inference_server.settings import settings class RedisQueue: def __init__( self, redis_cl...
This is type hinted to return `None` but may not
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
""" Helper function for patching HF language models. Currently supports: GPTNeoX-based models Limitations: - Flash attention requires CUDA and fp16/bf16 training. It also requires contiguous attention masks. - Residual dropout does not support multi-GPU training without DeepDpeed. """ ...
`and not resid_pdrop` would also be possible.
Helper function for patching HF language models. Currently supports: GPTNeoX-based models Limitations: - Flash attention requires CUDA and fp16/bf16 training. It also requires contiguous attention masks. - Residual dropout does not support multi-GPU training without DeepDpeed. """ globa...
@@ -127,6 +127,9 @@ def patch_model( if resid_pdrop is not None and (resid_pdrop < 0 or resid_pdrop > 1.0): raise ValueError("Invalid argument: `resid_pdrop` must be between 0.0 and 1.0") + if not flash_attention and (resid_pdrop is None or resid_pdrop == 0.0):
model/model_training/models/patching.py
26
Python
0.214
suggestion
45
51
51
false
Fix GPTNeoX-20B training
2,240
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
dvruette
Review this pull request change. Language: Python File: model/model_training/models/patching.py PR Title: Fix GPTNeoX-20B training BEFORE CODE: """ Helper function for patching HF language models. Currently supports: GPTNeoX-based models Limitations: - Flash attention requires CUDA and fp16/b...
`and not resid_pdrop` would also be possible.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
type AppPropsWithLayout = AppProps & { Component: NextPageWithLayout; env: typeof process.env; cookie: string; }; const swrConfig: SWRConfiguration = { revalidateOnFocus: false, revalidateOnMount: true, }; function MyApp({ Component, pageProps: { session, ...pageProps }, env, cookie }: AppPropsWithLayout) {...
could we maybe do it like this? ```ts process.env = new Proxy(env, { get(env, key) { const value = env[key]; if (!value) { throw new Error("Environment variable not set in _app.tsx") } return value; } ) ``` I think it is very easy to make this mistake, wh...
type AppPropsWithLayout = AppProps & { Component: NextPageWithLayout; env: typeof process.env; cookie: string; }; const swrConfig: SWRConfiguration = { revalidateOnFocus: false, revalidateOnMount: true, }; function MyApp({ Component, pageProps: { session, ...pageProps }, env, cookie }: AppPropsWithLayout) {...
@@ -1,43 +1,56 @@ import "../styles/globals.css"; import "focus-visible"; -import type { AppProps } from "next/app"; +import { boolean } from "boolean"; +import type { AppContext, AppProps } from "next/app"; import Head from "next/head"; import { SessionProvider } from "next-auth/react"; import { appWithTranslat...
website/src/pages/_app.tsx
26
TypeScript
1
suggestion
442
51
51
false
Expose env vars globally
2,244
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
notmd
Review this pull request change. Language: TypeScript File: website/src/pages/_app.tsx PR Title: Expose env vars globally BEFORE CODE: type AppPropsWithLayout = AppProps & { Component: NextPageWithLayout; env: typeof process.env; cookie: string; }; const swrConfig: SWRConfiguration = { revalidateOnFocus: f...
could we maybe do it like this? ```ts process.env = new Proxy(env, { get(env, key) { const value = env[key]; if (!value) { throw new Error("Environment variable not set in _app.tsx") } return value; } ) ``` I think it is very easy to make this mistake, wh...
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import "../styles/globals.css"; import "focus-visible"; import { boolean } from "boolean"; import type { AppContext, AppProps } from "next/app"; import Head from "next/head"; import { SessionProvider } from "next-auth/react"; import { appWithTranslation, useTranslation } from "next-i18next"; import React, { useEffect ...
can you check if this is still needed? I remember that I did some debugging, and this cookie field was always empty.
<> <Head> <meta name="description" key="description" content={t("index:description")} /> </Head> <FlagsProvider value={flags}> <Chakra cookie={cookie}> <SWRConfig value={swrConfig}> <SessionProvider session={session}>{page}</SessionProvider> </SWRCon...
@@ -46,5 +59,18 @@ function MyApp({ Component, pageProps: { session, cookies, ...pageProps } }: App </> ); } -export { getServerSideProps }; + +MyApp.getInitialProps = ({ ctx: { req } }: AppContext) => { + return { + env: { + INFERENCE_SERVER_HOST: process.env.INFERENCE_SERVER_HOST, + ENABLE_CHAT...
website/src/pages/_app.tsx
26
TypeScript
0.5
bug
116
77
31
false
Expose env vars globally
2,244
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
notmd
Review this pull request change. Language: TypeScript File: website/src/pages/_app.tsx PR Title: Expose env vars globally BEFORE CODE: import "../styles/globals.css"; import "focus-visible"; import { boolean } from "boolean"; import type { AppContext, AppProps } from "next/app"; import Head from "next/head"; impor...
can you check if this is still needed? I remember that I did some debugging, and this cookie field was always empty.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
"llama": TokenizerConfig(special_tokens=SpecialTokens("</s>", "</s>", sep_token="<s>")), "cerebras": TokenizerConfig(special_tokens=SpecialTokens("<|endoftext|>", "<|endoftext|>", "<|endoftext|>")), } def match_tokenizer_name(model_name: str) -> TokenizerConfig: """ Match a partial model name to a tok...
does this have to be specified? Are the other models released without a tokenizer-config? Otherwise this coud be removed .. the special handling for LLaMA was also removed already...
"gpt-neox": TokenizerConfig(special_tokens=SpecialTokens("<|padding|>", "<|endoftext|>", "<|endoftext|>")), "llama": TokenizerConfig(special_tokens=SpecialTokens("</s>", "</s>", sep_token="<s>")), "cerebras": TokenizerConfig(special_tokens=SpecialTokens("<|endoftext|>", "<|endoftext|>", "<|endoftext|>")), }...
@@ -189,6 +190,9 @@ def get_tokenizer(conf) -> transformers.AutoTokenizer: # explicitly specify LLaMATokenizer class until AutoTokenizer works # assumes that the tokenizer config is stored in the same directory as the model weights tokenizer = LLaMATokenizer.from_pretrained(conf.model_name) +...
model/model_training/utils.py
26
Python
0.429
question
182
51
51
false
Add support for Cerebras-GPT for training
2,276
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
olliestanley
Review this pull request change. Language: Python File: model/model_training/utils.py PR Title: Add support for Cerebras-GPT for training BEFORE CODE: "llama": TokenizerConfig(special_tokens=SpecialTokens("</s>", "</s>", sep_token="<s>")), "cerebras": TokenizerConfig(special_tokens=SpecialTokens("<|endoftex...
does this have to be specified? Are the other models released without a tokenizer-config? Otherwise this coud be removed .. the special handling for LLaMA was also removed already...
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import axios, { AxiosRequestConfig } from "axios"; import { JWT } from "next-auth/jwt"; import { ChatItem, InferenceMessage, InferencePostAssistantMessageParams, InferencePostPrompterMessageParams, ModelInfo, TrustedClient, } from "src/types/Chat"; import type { Readable } from "stream"; export class Oasst...
Is this the correct uuid in the data collection backend?
stream_events({ chat_id, message_id }: { chat_id: string; message_id: string }) { return this.request<Readable>(`/chats/${chat_id}/messages/${message_id}/events`, { headers: { Accept: "text/event-stream", Connection: "keep-alive", "Cache-Control": "no-cache, no-transform", }, ...
@@ -81,6 +75,13 @@ export class OasstInferenceClient { } export const createInferenceClient = (jwt: JWT) => { - const token = jwt.inferenceTokens?.access_token.access_token; + const info: TrustedClient = { + // TODO: use api key from env + api_key: "0000", + client: "website", + user_id: jwt.sub,
website/src/lib/oasst_inference_client.ts
26
TypeScript
0.214
question
56
88
32
false
Use trusted clients for inference auth
2,278
LAION-AI/Open-Assistant
29,137
Python
notmd
AbdBarho
Review this pull request change. Language: TypeScript File: website/src/lib/oasst_inference_client.ts PR Title: Use trusted clients for inference auth BEFORE CODE: import axios, { AxiosRequestConfig } from "axios"; import { JWT } from "next-auth/jwt"; import { ChatItem, InferenceMessage, InferencePostAssistan...
Is this the correct uuid in the data collection backend?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
TrustedClient: this.clientToken, }, }); return data; } inference_login() { return this.request("/auth/trusted", { method: "POST" }); } get_my_chats(): Promise<ChatItem[]> { return this.request("/chats"); } async create_chat(): Promise<ChatItem> { const create = () => thi...
Can we check for the http status here?
TrustedClient: this.clientToken, }, }); return data; } inference_login() { return this.request("/auth/trusted", { method: "POST" }); } get_my_chats(): Promise<ChatItem[]> { return this.request("/chats"); } async create_chat(): Promise<ChatItem> { const create = () => thi...
@@ -3,45 +3,49 @@ import { JWT } from "next-auth/jwt"; import { ChatItem, InferenceMessage, - InferencePostPrompterMessageParams, InferencePostAssistantMessageParams, + InferencePostPrompterMessageParams, ModelInfo, + TrustedClient, } from "src/types/Chat"; import type { Readable } from "stream"; e...
website/src/lib/oasst_inference_client.ts
26
TypeScript
0.071
question
38
51
51
false
Use trusted clients for inference auth
2,278
LAION-AI/Open-Assistant
29,137
Python
notmd
AbdBarho
Review this pull request change. Language: TypeScript File: website/src/lib/oasst_inference_client.ts PR Title: Use trusted clients for inference auth BEFORE CODE: TrustedClient: this.clientToken, }, }); return data; } inference_login() { return this.request("/auth/trusted", { method:...
Can we check for the http status here?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { withoutRole } from "src/lib/auth"; import { createApiClientFromUser } from "src/lib/oasst_client_factory"; import { getBackendUserCore } from "src/lib/users"; const handler = withoutRole("banned", async (req, res, token) => { const user = await getBackendUserCore(token.sub); const oasstApiClient = createA...
You can deconstruct the result here
import { withoutRole } from "src/lib/auth"; import { createApiClientFromUser } from "src/lib/oasst_client_factory"; import { getBackendUserCore } from "src/lib/users"; const handler = withoutRole("banned", async (req, res, token) => { const user = await getBackendUserCore(token.sub); const oasstApiClient = createA...
@@ -6,7 +6,7 @@ const handler = withoutRole("banned", async (req, res, token) => { const user = await getBackendUserCore(token.sub); const oasstApiClient = createApiClientFromUser(user); if (req.method === "GET") { - const tos_acceptance_date = await oasstApiClient.fetch_tos_acceptance(user); + const tos...
website/src/pages/api/tos.ts
9
TypeScript
0.071
suggestion
35
19
19
false
Use trusted clients for inference auth
2,278
LAION-AI/Open-Assistant
29,137
Python
notmd
AbdBarho
Review this pull request change. Language: TypeScript File: website/src/pages/api/tos.ts PR Title: Use trusted clients for inference auth BEFORE CODE: import { withoutRole } from "src/lib/auth"; import { createApiClientFromUser } from "src/lib/oasst_client_factory"; import { getBackendUserCore } from "src/lib/users...
You can deconstruct the result here
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
@app.middleware("http") async def log_exceptions(request: fastapi.Request, call_next): try: response = await call_next(request) except Exception: logger.exception("Exception in request") raise return response def terminate_server(signum, frame): logger.warning(f"Signal {signum...
Just a preference really but I feel a one-liner is clearer here `eos_token = tokenizer.eos_token if hasattr(tokenizer, "eos_token") else ""`
@app.middleware("http") async def log_exceptions(request: fastapi.Request, call_next): try: response = await call_next(request) except Exception: logger.exception("Exception in request") raise return response model_loaded: bool = False fully_loaded: bool = False model_input_queue...
@@ -42,6 +47,51 @@ def terminate_server(signum, frame): model: transformers.PreTrainedModel tokenizer: transformers.PreTrainedTokenizer +fully_loaded: bool = False +model_input_queue: Queue = Queue() + + +def model_thread(): + request: interface.GenerateStreamRequest + output_queue: Queue + eos_token = ""
inference/worker/basic_hf_server.py
26
Python
0.571
suggestion
143
51
51
false
changed basic hf server to support quantization and streaming
2,293
LAION-AI/Open-Assistant
29,137
Python
olliestanley
yk
Review this pull request change. Language: Python File: inference/worker/basic_hf_server.py PR Title: changed basic hf server to support quantization and streaming BEFORE CODE: @app.middleware("http") async def log_exceptions(request: fastapi.Request, call_next): try: response = await call_next(request...
Just a preference really but I feel a one-liner is clearer here `eos_token = tokenizer.eos_token if hasattr(tokenizer, "eos_token") else ""`
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# get the world size in deeepspeed if conf["deepspeed"]: conf["world_size"] = int(os.getenv("WORLD_SIZE", default="1")) else: conf["world_size"] = 1 # Override config from command-line parser = argparse.ArgumentParser() for key, value in conf.items(): type_ = type(value...
line is duplicate of previous line ```suggestion ```
# get the world size in deeepspeed if conf["deepspeed"]: conf["world_size"] = int(os.getenv("WORLD_SIZE", default="1")) else: conf["world_size"] = 1 # Override config from command-line parser = argparse.ArgumentParser() for key, value in conf.items(): type_ = type(value...
@@ -184,6 +184,8 @@ def main(): init_rng(training_conf) + init_rng(training_conf) +
model/model_training/trainer_rm.py
26
Python
0.571
refactor
54
51
51
false
changed basic hf server to support quantization and streaming
2,293
LAION-AI/Open-Assistant
29,137
Python
dvruette
yk
Review this pull request change. Language: Python File: model/model_training/trainer_rm.py PR Title: changed basic hf server to support quantization and streaming BEFORE CODE: # get the world size in deeepspeed if conf["deepspeed"]: conf["world_size"] = int(os.getenv("WORLD_SIZE", default="1")) ...
line is duplicate of previous line ```suggestion ```
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import websocket import work from loguru import logger from oasst_shared import model_configs from oasst_shared.schemas import inference from settings import settings def terminate_worker(signum, frame): logger.warning(f"Signal {signum}. Terminating worker...") sys.exit(0) def main(): signal.signal(sign...
can be removed with latest HF version (4.28.0.dev0)
import websocket import work from loguru import logger from oasst_shared import model_configs from oasst_shared.schemas import inference from settings import settings def terminate_worker(signum, frame): logger.warning(f"Signal {signum}. Terminating worker...") sys.exit(0) def main(): signal.signal(sign...
@@ -31,10 +31,11 @@ def main(): if model_config.is_lorem: tokenizer = None - elif model_config.is_llama: - tokenizer: transformers.PreTrainedTokenizer = transformers.LlamaTokenizer.from_pretrained(model_config.model_id) + # elif model_config.is_llama: + # tokenizer: transformers.PreT...
inference/worker/__main__.py
26
Python
0.286
suggestion
51
51
51
false
changed basic hf server to support quantization and streaming
2,293
LAION-AI/Open-Assistant
29,137
Python
dvruette
yk
Review this pull request change. Language: Python File: inference/worker/__main__.py PR Title: changed basic hf server to support quantization and streaming BEFORE CODE: import websocket import work from loguru import logger from oasst_shared import model_configs from oasst_shared.schemas import inference from sett...
can be removed with latest HF version (4.28.0.dev0)
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
name = list(data_config.keys())[0] # first copy the dict, then remove the size and fraction kwargs = copy.deepcopy(data_config[name]) kwargs.pop("fraction", None) kwargs.pop("size", None) return name, kwargs else: return data_config, {} def get_dataset( ...
Is this special return handling really necessary (`return_datasets_as_list` etc)? It is possible to access the list of datasets via the `datasets` member of a `ConcatDataset` instance.
name = list(data_config.keys())[0] # first copy the dict, then remove the size and fraction kwargs = copy.deepcopy(data_config[name]) kwargs.pop("fraction", None) kwargs.pop("size", None) return name, kwargs else: return data_config, {} def get_dataset( ...
@@ -365,6 +367,8 @@ def get_dataset(conf, mode="sft"): if val is not None: evals[dataset_name] = Subset(val, list(range(min(len(val), conf.eval_size)))) if conf.eval_size else val + if return_datasets_as_list:
model/model_training/utils.py
26
Python
0.5
question
184
51
51
false
add dataset counts script
2,294
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
CloseChoice
Review this pull request change. Language: Python File: model/model_training/utils.py PR Title: add dataset counts script BEFORE CODE: name = list(data_config.keys())[0] # first copy the dict, then remove the size and fraction kwargs = copy.deepcopy(data_config[name]) kwargs.pop("f...
Is this special return handling really necessary (`return_datasets_as_list` etc)? It is possible to access the list of datasets via the `datasets` member of a `ConcatDataset` instance.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
""" def preprocess_dialogue(self, text): """ trim prefix text to last two pairs Outlier example Assistant answered empty string: Assistant: Human: That makes sense, I agree with that, though there are many situations that aren't considered justice, like sending ...
This are changes in the reward/instructor folder. They are not used for the trainer_rm code. I suggest to remove these changes.
""" def preprocess_dialogue(self, text): """ trim prefix text to last two pairs Outlier example Assistant answered empty string: Assistant: Human: That makes sense, I agree with that, though there are many situations that aren't considered justice, like sending ...
@@ -261,11 +261,16 @@ def preprocess_dialogue(self, text): return "Human:".join(last_two_convo) return "Human: " + "Human:".join(last_two_convo) - def __init__(self, split="train", sep_token="<sep>") -> None: + def __init__(self, split="train", sep_token="<sep>", mode=None) -> None: ...
model/reward/instructor/rank_datasets.py
26
Python
0.429
suggestion
127
51
51
false
two more datasets
2,301
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
mikegarts
Review this pull request change. Language: Python File: model/reward/instructor/rank_datasets.py PR Title: two more datasets BEFORE CODE: """ def preprocess_dialogue(self, text): """ trim prefix text to last two pairs Outlier example Assistant answered empty string: Ass...
This are changes in the reward/instructor folder. They are not used for the trainer_rm code. I suggest to remove these changes.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { AnimatedCircles } from "./AnimatedCircles"; import { Container } from "./Container"; export function Hero() { const { t } = useTranslation(["index", "common"]); const { colorMode } = useColorMode(); const pTextColor = colorMode === "light" ? "text-gray-600" : "text-white"; const fancyTextGradientClass...
do we also need to have the `pTextColor` as part of the class name just like above? does it look good in dark / light mode?
import { AnimatedCircles } from "./AnimatedCircles"; import { Container } from "./Container"; export function Hero() { const { t } = useTranslation(["index", "common"]); const { colorMode } = useColorMode(); const pTextColor = colorMode === "light" ? "text-gray-600" : "text-white"; const fancyTextGradientClass...
@@ -27,6 +30,20 @@ export function Hero() { </Text> <Text className={`mt-6 text-lg ${pTextColor}`}>{t("blurb")}</Text> <Text className={`mt-6 text-lg ${pTextColor}`}>{t("blurb1")}</Text> + <Box className="mt-6 flex gap-6">
website/src/components/Hero.tsx
26
TypeScript
0.5
question
123
51
51
false
Added CTA buttons to the frontpage
2,302
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
yk
Review this pull request change. Language: TypeScript File: website/src/components/Hero.tsx PR Title: Added CTA buttons to the frontpage BEFORE CODE: import { AnimatedCircles } from "./AnimatedCircles"; import { Container } from "./Container"; export function Hero() { const { t } = useTranslation(["index", "comm...
do we also need to have the `pTextColor` as part of the class name just like above? does it look good in dark / light mode?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
If you find the data useful, please cite the paper. The data format is very simple -- each line of the jsonl files contains a pair of texts, one "chosen" and one "rejected". valid train size : 160780 """ def preprocess_dialogue(self, text): """ trim prefix text to l...
There are now duplicate changes to my 5 minutes earlier submitted PR #2306.
If you find the data useful, please cite the paper. The data format is very simple -- each line of the jsonl files contains a pair of texts, one "chosen" and one "rejected". valid train size : 160780 """ def preprocess_dialogue(self, text): """ trim prefix text to l...
@@ -261,16 +261,11 @@ def preprocess_dialogue(self, text): return "Human:".join(last_two_convo) return "Human: " + "Human:".join(last_two_convo) - def __init__(self, split="train", sep_token="<sep>", mode=None) -> None: + def __init__(self, split="train", sep_token="<sep>") -> None: ...
model/reward/instructor/rank_datasets.py
26
Python
0.286
refactor
75
51
51
false
revert instructor code and fix a bug in anthropic ds parsing
2,307
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
mikegarts
Review this pull request change. Language: Python File: model/reward/instructor/rank_datasets.py PR Title: revert instructor code and fix a bug in anthropic ds parsing BEFORE CODE: If you find the data useful, please cite the paper. The data format is very simple -- each line of the jsonl files cont...
There are now duplicate changes to my 5 minutes earlier submitted PR #2306.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
from model_training.custom_datasets.rank_datasets import AnthropicRLHF, HFDataset def load_anthroopic_rlhf(): train = AnthropicRLHF(split="train") validation = AnthropicRLHF(split="test") print(f"AnthropicRLHF extra dataset size: {len(train)}, {len(validation)}") return train, validation def load_...
typo: ```suggestion def load_anthropic_rlhf(): ```
from model_training.custom_datasets.rank_datasets import AnthropicRLHF, HFDataset def load_anthropic_rlhf(): train = AnthropicRLHF(split="train") validation = AnthropicRLHF(split="test") print(f"AnthropicRLHF extra dataset size: {len(train)}, {len(validation)}") return train, validation def load_o...
@@ -1,10 +1,9 @@ -from model_training.custom_datasets.rank_datasets import HFDataset -from reward.instructor.rank_datasets import AnthropicRLHF +from model_training.custom_datasets.rank_datasets import AnthropicRLHF, HFDataset def load_anthroopic_rlhf():
model/model_training/custom_datasets/extra_rm_datasets.py
4
Python
0.571
suggestion
53
26
26
false
revert instructor code and fix a bug in anthropic ds parsing
2,307
LAION-AI/Open-Assistant
29,137
Python
dvruette
mikegarts
Review this pull request change. Language: Python File: model/model_training/custom_datasets/extra_rm_datasets.py PR Title: revert instructor code and fix a bug in anthropic ds parsing BEFORE CODE: from model_training.custom_datasets.rank_datasets import AnthropicRLHF, HFDataset def load_anthroopic_rlhf(): tr...
typo: ```suggestion def load_anthropic_rlhf(): ```
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
parser.add_argument("--no-deepspeed", dest="deepspeed", action="store_false") parser.add_argument("--wandb-entity", type=str, default="open-assistant") parser.add_argument("--rng_seed", type=int, help="rng seed") parser.set_defaults(deepspeed=False) if notebook: args, remaining = parser.par...
I don't think this logic is correct, but I can correct it after merge in the improve_small_rm branch..
parser.add_argument("--wandb-entity", type=str, default="open-assistant") parser.add_argument("--rng_seed", type=int, help="rng seed") parser.set_defaults(deepspeed=False) if notebook: args, remaining = parser.parse_known_args(notebook_args) else: args, remaining = parser.parse_know...
@@ -158,7 +160,7 @@ def argument_parsing(notebook=False, notebook_args=None): conf["wandb_entity"] = args.wandb_entity conf["local_rank"] = args.local_rank conf["deepspeed"] = args.deepspeed - if args.rng_seed is not None: + if "rng_seed" not in conf and args.rng_seed is not None:
model/model_training/trainer_rm.py
26
Python
0.357
suggestion
102
51
51
false
fix deepspeed issue on trainer_rm.py, add crossentropy support
2,321
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
theblackcat102
Review this pull request change. Language: Python File: model/model_training/trainer_rm.py PR Title: fix deepspeed issue on trainer_rm.py, add crossentropy support BEFORE CODE: parser.add_argument("--no-deepspeed", dest="deepspeed", action="store_false") parser.add_argument("--wandb-entity", type=str, defau...
I don't think this logic is correct, but I can correct it after merge in the improve_small_rm branch..
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
def get_metrics(conf, tokenizer): # the reason behind using a list is that we might want to extend the list of our # metrics in the future for more thorough evaluation metrics, preprocess_fns = [evaluate.load("accuracy")], [default_preprocess] # if any(dataset in QA_DATASETS for dataset in conf.dataset...
hm. why was the dtype specification here removed .. ?
def get_metrics(conf, tokenizer): # the reason behind using a list is that we might want to extend the list of our # metrics in the future for more thorough evaluation metrics, preprocess_fns = [evaluate.load("accuracy")], [default_preprocess] # if any(dataset in QA_DATASETS for dataset in conf.dataset...
@@ -296,12 +299,14 @@ def get_model(conf, tokenizer, pad_vocab_size_to_multiple_of=16): if conf.is_reward_model: if "pythia" in conf.model_name: - model = GPTNeoXRewardModel.from_pretrained(conf.model_name, cache_dir=conf.cache_dir, torch_dtype=dtype)
model/model_training/utils.py
26
Python
0.429
question
53
51
51
false
fix deepspeed issue on trainer_rm.py, add crossentropy support
2,321
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
theblackcat102
Review this pull request change. Language: Python File: model/model_training/utils.py PR Title: fix deepspeed issue on trainer_rm.py, add crossentropy support BEFORE CODE: def get_metrics(conf, tokenizer): # the reason behind using a list is that we might want to extend the list of our # metrics in the futu...
hm. why was the dtype specification here removed .. ?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import fastapi import pydantic import sqlalchemy.orm import sqlmodel from loguru import logger from oasst_inference_server import database, models from oasst_shared.schemas import inference class UserChatRepository(pydantic.BaseModel): session: database.AsyncSession user_id: str = pydantic.Field(..., min_leng...
could we leave this sorted by date? this has the advantage of being functional regardless of which id type we use. Also perhaps slightly faster but not that much.
import fastapi import pydantic import sqlalchemy.orm import sqlmodel from loguru import logger from oasst_inference_server import database, models from oasst_shared.schemas import inference class UserChatRepository(pydantic.BaseModel): session: database.AsyncSession user_id: str = pydantic.Field(..., min_leng...
@@ -17,7 +17,7 @@ class Config: async def get_chats(self) -> list[models.DbChat]: query = sqlmodel.select(models.DbChat) query = query.where(models.DbChat.user_id == self.user_id) - query = query.order_by(models.DbChat.created_at.desc()) + query = query.order_by(models.DbChat.id.des...
inference/server/oasst_inference_server/user_chat_repository.py
20
Python
0.571
style
162
45
45
false
inference: use uuid v7 for most of table
2,327
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
notmd
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/user_chat_repository.py PR Title: inference: use uuid v7 for most of table BEFORE CODE: import fastapi import pydantic import sqlalchemy.orm import sqlmodel from loguru import logger from oasst_inference_server import da...
could we leave this sorted by date? this has the advantage of being functional regardless of which id type we use. Also perhaps slightly faster but not that much.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import datetime import enum from uuid import uuid4 import sqlalchemy as sa import sqlalchemy.dialects.postgresql as pg from loguru import logger from oasst_inference_server.settings import settings from oasst_shared.schemas import inference from sqlmodel import Field, Relationship, SQLModel from uuid_extensions import...
is the lambda necessary or could it be `default_factory=uuid7str` ?
import datetime import enum from uuid import uuid4 import sqlalchemy as sa import sqlalchemy.dialects.postgresql as pg from loguru import logger from oasst_inference_server.settings import settings from oasst_shared.schemas import inference from sqlmodel import Field, Relationship, SQLModel from uuid_extensions import...
@@ -17,7 +18,7 @@ class WorkerEventType(str, enum.Enum): class DbWorkerComplianceCheck(SQLModel, table=True): __tablename__ = "worker_compliance_check" - id: str = Field(default_factory=lambda: str(uuid4()), primary_key=True) + id: str = Field(default_factory=lambda: uuid7str(), primary_key=True)
inference/server/oasst_inference_server/models/worker.py
21
Python
0.429
question
67
46
46
false
inference: use uuid v7 for most of table
2,327
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
notmd
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/models/worker.py PR Title: inference: use uuid v7 for most of table BEFORE CODE: import datetime import enum from uuid import uuid4 import sqlalchemy as sa import sqlalchemy.dialects.postgresql as pg from loguru import ...
is the lambda necessary or could it be `default_factory=uuid7str` ?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
from collections import defaultdict from typing import List import numpy as np from datasets import load_dataset from torch.utils.data import Dataset SEED = 2020 class SHPDataset(Dataset): """ Dataset class to load stanfordnlp/SHP for Reward Modeling """ name = "SHP" def __init__(self, split):...
Propose to just merge rank dataset for webgpt with SFT and RL mode under qa_datasets.py See [here](https://github.com/LAION-AI/Open-Assistant/blob/rm-fixes/model/model_training/custom_datasets/qa_datasets.py#L194)
import random from collections import defaultdict from typing import List import numpy as np from datasets import load_dataset from torch.utils.data import Dataset SEED = 2020 class SHPDataset(Dataset): """ Dataset class to load stanfordnlp/SHP for Reward Modeling """ name = "SHP" def __init__...
model/model_training/custom_datasets/rank_datasets.py
1
Python
0.429
suggestion
218
26
26
false
Improve scores of small 1.4B reward model..
2,329
LAION-AI/Open-Assistant
29,137
Python
theblackcat102
andreaskoepf
Review this pull request change. Language: Python File: model/model_training/custom_datasets/rank_datasets.py PR Title: Improve scores of small 1.4B reward model.. BEFORE CODE: from collections import defaultdict from typing import List import numpy as np from datasets import load_dataset from torch.utils.data imp...
Propose to just merge rank dataset for webgpt with SFT and RL mode under qa_datasets.py See [here](https://github.com/LAION-AI/Open-Assistant/blob/rm-fixes/model/model_training/custom_datasets/qa_datasets.py#L194)
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
""" High level functions for model training """ from model_training.custom_datasets.extra_rm_datasets import ( load_anthropic_rlhf, load_hellaswag, load_open_ai_summarize_from_feedback, load_shp, ) from model_training.custom_datasets.instruction import INSTRUCTION_DATASETS, InstructionDataset from m...
I would prefer to leave WebGPTQA as WebGPT and remove the WebGPTRank under rank_dataset as the ranking function was supported in the original WebGPT ( under qa_dataset )
""" High level functions for model training """ from typing import Optional import numpy as np from model_training.custom_datasets.extra_rm_datasets import load_anthropic_rlhf, load_hellaswag, load_shp from model_training.custom_datasets.instruction import INSTRUCTION_DATASETS, InstructionDataset from model_traini...
model/model_training/custom_datasets/__init__.py
1
Python
0.429
suggestion
169
26
26
false
Improve scores of small 1.4B reward model..
2,329
LAION-AI/Open-Assistant
29,137
Python
theblackcat102
andreaskoepf
Review this pull request change. Language: Python File: model/model_training/custom_datasets/__init__.py PR Title: Improve scores of small 1.4B reward model.. BEFORE CODE: """ High level functions for model training """ from model_training.custom_datasets.extra_rm_datasets import ( load_anthropic_rlhf, ...
I would prefer to leave WebGPTQA as WebGPT and remove the WebGPTRank under rank_dataset as the ranking function was supported in the original WebGPT ( under qa_dataset )
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
from model_training.custom_datasets.rank_datasets import AnthropicRLHF, HellaSwagDataset, HFDataset, SHPDataset from torch.utils.data import Dataset def load_anthropic_rlhf() -> tuple[Dataset, Dataset]: train = AnthropicRLHF(split="train") validation = AnthropicRLHF(split="test") print(f"AnthropicRLHF dat...
Could we use Tuple instead of tuple? I had some bad backward compatibility on Python3.8 (no other version choice ) with these static typing.
from model_training.custom_datasets.rank_datasets import AnthropicRLHF, HellaSwagDataset, SHPDataset from torch.utils.data import Dataset def load_anthropic_rlhf() -> tuple[Dataset, Dataset]: train = AnthropicRLHF(split="train") validation = AnthropicRLHF(split="test") return train, validation def load_...
model/model_training/custom_datasets/extra_rm_datasets.py
1
Python
0.429
suggestion
141
26
21
false
Improve scores of small 1.4B reward model..
2,329
LAION-AI/Open-Assistant
29,137
Python
theblackcat102
andreaskoepf
Review this pull request change. Language: Python File: model/model_training/custom_datasets/extra_rm_datasets.py PR Title: Improve scores of small 1.4B reward model.. BEFORE CODE: from model_training.custom_datasets.rank_datasets import AnthropicRLHF, HellaSwagDataset, HFDataset, SHPDataset from torch.utils.data i...
Could we use Tuple instead of tuple? I had some bad backward compatibility on Python3.8 (no other version choice ) with these static typing.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { withoutRole } from "src/lib/auth"; import { createApiClientFromUser } from "src/lib/oasst_client_factory"; import { getBackendUserCore } from "src/lib/users"; const handler = withoutRole("banned", async (req, res, token) => { let userid: string; if (req.query.uid) { userid = typeof req.query.uid === "...
Also can you check the current user has any mod or admin role herer? We dont want to expose stats to every one.
import { ROLES } from "src/components/RoleSelect"; import { withoutRole } from "src/lib/auth"; import { createApiClientFromUser } from "src/lib/oasst_client_factory"; import { getBackendUserCore } from "src/lib/users"; const handler = withoutRole("banned", async (req, res, token) => { let userid: string; const isM...
@@ -3,7 +3,14 @@ import { createApiClientFromUser } from "src/lib/oasst_client_factory"; import { getBackendUserCore } from "src/lib/users"; const handler = withoutRole("banned", async (req, res, token) => { - const user = await getBackendUserCore(token.sub); + let userid: string; + if (req.query.uid) {
website/src/pages/api/user_stats.ts
7
TypeScript
0.429
suggestion
111
20
25
false
stats are shown on the admin
2,330
LAION-AI/Open-Assistant
29,137
Python
notmd
vivasvan1
Review this pull request change. Language: TypeScript File: website/src/pages/api/user_stats.ts PR Title: stats are shown on the admin BEFORE CODE: import { withoutRole } from "src/lib/auth"; import { createApiClientFromUser } from "src/lib/oasst_client_factory"; import { getBackendUserCore } from "src/lib/users"; ...
Also can you check the current user has any mod or admin role herer? We dont want to expose stats to every one.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { boolean } from "boolean"; import { Head, Html, Main, NextScript } from "next/document"; export default function Document() { return ( <Html className="h-full antialiased" lang="en"> <Head> <link rel="shortcut icon" type="image/png" href="/images/logos/favicon.png" /> <script ...
is there really no other way? ~~can we move this code into the body of the react function?~~ ok this function is executed server-side only.
import { Head, Html, Main, NextScript } from "next/document"; export default function Document() { return ( <Html className="h-full antialiased" lang="en"> <Head> <link rel="shortcut icon" type="image/png" href="/images/logos/favicon.png" /> </Head> <body className="flex h-full flex-col...
@@ -1,10 +1,27 @@ +import { boolean } from "boolean"; import { Head, Html, Main, NextScript } from "next/document"; export default function Document() { return ( <Html className="h-full antialiased" lang="en"> <Head> <link rel="shortcut icon" type="image/png" href="/images/logos/favicon.png"...
website/src/pages/_document.tsx
10
TypeScript
0.429
refactor
145
35
16
false
Use SSR for every pages
2,334
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
notmd
Review this pull request change. Language: TypeScript File: website/src/pages/_document.tsx PR Title: Use SSR for every pages BEFORE CODE: import { boolean } from "boolean"; import { Head, Html, Main, NextScript } from "next/document"; export default function Document() { return ( <Html className="h-full ant...
is there really no other way? ~~can we move this code into the body of the react function?~~ ok this function is executed server-side only.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { boolean } from "boolean"; import { withoutRole } from "src/lib/auth"; import { createInferenceClient } from "src/lib/oasst_inference_client"; import { InferencePostAssistantMessageParams } from "src/types/Chat"; const handler = withoutRole("banned", async (req, res, token) => { if (!boolean(process.env.ENAB...
this line is repeated too many times, maybe we can re-add the `isChatEnabled` but we can use the new `getEnv()` in it
import { withoutRole } from "src/lib/auth"; import { isChatEnable } from "src/lib/isChatEnable"; import { createInferenceClient } from "src/lib/oasst_inference_client"; import { InferencePostAssistantMessageParams } from "src/types/Chat"; const handler = withoutRole("banned", async (req, res, token) => { if (!isChat...
@@ -1,8 +1,12 @@ +import { boolean } from "boolean"; import { withoutRole } from "src/lib/auth"; import { createInferenceClient } from "src/lib/oasst_inference_client"; import { InferencePostAssistantMessageParams } from "src/types/Chat"; const handler = withoutRole("banned", async (req, res, token) => { + if (!...
website/src/pages/api/chat/assistant_message.ts
7
TypeScript
0.571
suggestion
117
21
21
false
Use SSR for every pages
2,334
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
notmd
Review this pull request change. Language: TypeScript File: website/src/pages/api/chat/assistant_message.ts PR Title: Use SSR for every pages BEFORE CODE: import { boolean } from "boolean"; import { withoutRole } from "src/lib/auth"; import { createInferenceClient } from "src/lib/oasst_inference_client"; import { I...
this line is repeated too many times, maybe we can re-add the `isChatEnabled` but we can use the new `getEnv()` in it
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
self.pairs.append((prefix, human, answer)) else: self.pairs.append(("", human, answer)) # Does this make sense? prefix += "{}{}{}{}".format( "Question:", ...
could be tuple instead of list
if convo_round["round"] > 2: self.pairs.append((prefix, human, answer)) else: self.pairs.append(("", human, answer)) # Does this make sense? prefix += "{}{}{}{}".forma...
@@ -419,37 +420,78 @@ def __getitem__(self, index): return self.pairs[index] -class AlpacaBase(Dataset): - def __init__(self, dataset_name: str, mode: str, cache_dir: str = None) -> None: +class AlpacaBaseDataset(Dataset): + def __init__(self, data: list, mode: str): super().__init__() + ...
model/model_training/custom_datasets/qa_datasets.py
26
Python
0.143
suggestion
30
51
51
false
Add alpaca reverse augmentation possibility
2,342
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
CloseChoice
Review this pull request change. Language: Python File: model/model_training/custom_datasets/qa_datasets.py PR Title: Add alpaca reverse augmentation possibility BEFORE CODE: self.pairs.append((prefix, human, answer)) else: self.pairs.a...
could be tuple instead of list
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
def __getitem__(self, index): return self.pairs[index] class AlpacaBaseDataset(Dataset): def __init__(self, data: list, mode: str): super().__init__() self.data = data if mode not in ["sft", "rl"]: raise NotImplementedError( f"Alpaca Dataset for mode...
If these classes don't add any functionality they could be removed (i.e. base class be used directly).
def __getitem__(self, index): return self.pairs[index] class AlpacaBaseDataset(Dataset): def __init__(self, data: list, mode: str): super().__init__() self.data = data if mode not in ("sft", "rl"): raise NotImplementedError( f"Alpaca Dataset for mod...
@@ -419,37 +420,78 @@ def __getitem__(self, index): return self.pairs[index] -class AlpacaBase(Dataset): - def __init__(self, dataset_name: str, mode: str, cache_dir: str = None) -> None: +class AlpacaBaseDataset(Dataset): + def __init__(self, data: list, mode: str): super().__init__() + ...
model/model_training/custom_datasets/qa_datasets.py
26
Python
0.429
suggestion
103
51
51
false
Add alpaca reverse augmentation possibility
2,342
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
CloseChoice
Review this pull request change. Language: Python File: model/model_training/custom_datasets/qa_datasets.py PR Title: Add alpaca reverse augmentation possibility BEFORE CODE: def __getitem__(self, index): return self.pairs[index] class AlpacaBaseDataset(Dataset): def __init__(self, data: list, mod...
If these classes don't add any functionality they could be removed (i.e. base class be used directly).
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
def __getitem__(self, index): question, answer = self.data[index] if self.mode == "sft": return (question, answer) elif self.mode == "rl": return (question,) class AlpacaDataset(AlpacaBaseDataset): pass class CodeAlpacaDataset(AlpacaBaseDataset): pass d...
base class type annotation for factory function would be better imo
return len(self.data) def __getitem__(self, index): question, answer = self.data[index] if self.mode == "sft": return (question, answer) elif self.mode == "rl": return (question,) def load_alpaca_dataset( dataset_name: str, val_split: float, cac...
@@ -419,37 +420,78 @@ def __getitem__(self, index): return self.pairs[index] -class AlpacaBase(Dataset): - def __init__(self, dataset_name: str, mode: str, cache_dir: str = None) -> None: +class AlpacaBaseDataset(Dataset): + def __init__(self, data: list, mode: str): super().__init__() + ...
model/model_training/custom_datasets/qa_datasets.py
26
Python
0.429
suggestion
67
51
51
false
Add alpaca reverse augmentation possibility
2,342
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
CloseChoice
Review this pull request change. Language: Python File: model/model_training/custom_datasets/qa_datasets.py PR Title: Add alpaca reverse augmentation possibility BEFORE CODE: def __getitem__(self, index): question, answer = self.data[index] if self.mode == "sft": return (question, a...
base class type annotation for factory function would be better imo
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
dataset_name = dataset_name.lower() if dataset_name in QA_DATASETS: dataset = QADataset(dataset_name, data_path, "train") if not dataset.no_val: eval = QADataset(dataset_name, data_path, "validation") train = dataset elif dataset_name in SUMMARIZATION_DATASETS: ...
use immutable tuple instead of list
if mode == "rm": assert dataset_name in RM_DATASETS, f"Dataset {dataset_name} not supported for reward modeling" data_path = data_path or conf.cache_dir dataset_name = dataset_name.lower() if dataset_name in QA_DATASETS: dataset = QADataset(dataset_name, data_path, "train") if ...
@@ -114,10 +113,8 @@ def get_one_dataset( dataset = DiveMT() elif dataset_name == "webgpt": dataset = WebGPT(mode=mode) - elif dataset_name == "alpaca": - dataset = Alpaca(mode=mode, cache_dir=data_path) - elif dataset_name == "code_alpaca": - dataset = CodeAlpaca(mode=mode, c...
model/model_training/custom_datasets/__init__.py
26
Python
0.143
suggestion
35
51
51
false
Add alpaca reverse augmentation possibility
2,342
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
CloseChoice
Review this pull request change. Language: Python File: model/model_training/custom_datasets/__init__.py PR Title: Add alpaca reverse augmentation possibility BEFORE CODE: dataset_name = dataset_name.lower() if dataset_name in QA_DATASETS: dataset = QADataset(dataset_name, data_path, "train") ...
use immutable tuple instead of list
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
pairs = self._partition_list(truncated_dialogue, 2) # add previous history to conversation pairs # e.g. [[Q1, A1], [Q2, A2]] -> [[Q1, A1], [Q1, A1, Q2, A2]] pairs = list(accumulate(pairs, lambda x, y: x + y)) return pairs def __init__(self, cache_dir: str...
TODO: Change return depending on mode
""" Open / close book QA datasets """ import copy import glob import json import os import re from collections import defaultdict from pathlib import Path from urllib.request import urlopen import numpy as np from datasets import load_dataset from torch.utils.data import Dataset # @agoryuno contributed this re_re...
@@ -453,3 +456,64 @@ def __init__(self, mode: str = "sft", cache_dir: str = None) -> None: class CodeAlpaca(AlpacaBase): def __init__(self, mode: str = "sft", cache_dir: str = None) -> None: super().__init__(dataset_name="sahil2801/CodeAlpaca-20k", mode=mode, cache_dir=cache_dir) + + +class Vicuna(Datase...
model/model_training/custom_datasets/qa_datasets.py
26
Python
0.143
suggestion
37
27
512
false
Add vicuna dataset
2,364
LAION-AI/Open-Assistant
29,137
Python
CloseChoice
CloseChoice
Review this pull request change. Language: Python File: model/model_training/custom_datasets/qa_datasets.py PR Title: Add vicuna dataset BEFORE CODE: pairs = self._partition_list(truncated_dialogue, 2) # add previous history to conversation pairs # e.g. [[Q1, A1], [Q2, A2]] -> [[...
TODO: Change return depending on mode
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
Returns: list[list]: list of sublists with length chunk_size """ return [l[i : i + chunk_size] for i in range(0, len(l), chunk_size)] def process_vicuna_conversations(self, data: dict[str, Any], input_max_length: int) -> list[list[str]] | None: # Perform some sanity chec...
This is not yet correct, should just be the truncated dialogue
message = line["value"] if role != speaker: if role is not None: dialogue.append("\n".join(messages)) messages = [] role = speaker messages.append(message.strip()) if role is not None and len(messages) >...
@@ -453,3 +456,64 @@ def __init__(self, mode: str = "sft", cache_dir: str = None) -> None: class CodeAlpaca(AlpacaBase): def __init__(self, mode: str = "sft", cache_dir: str = None) -> None: super().__init__(dataset_name="sahil2801/CodeAlpaca-20k", mode=mode, cache_dir=cache_dir) + + +class Vicuna(Datase...
model/model_training/custom_datasets/qa_datasets.py
26
Python
0.286
suggestion
62
49
41
false
Add vicuna dataset
2,364
LAION-AI/Open-Assistant
29,137
Python
CloseChoice
CloseChoice
Review this pull request change. Language: Python File: model/model_training/custom_datasets/qa_datasets.py PR Title: Add vicuna dataset BEFORE CODE: Returns: list[list]: list of sublists with length chunk_size """ return [l[i : i + chunk_size] for i in range(0, len(l), chunk_siz...
This is not yet correct, should just be the truncated dialogue
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
from model_training.custom_datasets.toxic_conversation import ProsocialDialogue, ProsocialDialogueExplaination from model_training.custom_datasets.translation import WMT2019, DiveMT, TEDTalk from sklearn.model_selection import train_test_split from torch.utils.data import Dataset, Subset QA_DATASETS = list(QADataset.D...
please use ',' at the end to have one entry per line.
from model_training.custom_datasets.toxic_conversation import ProsocialDialogue, ProsocialDialogueExplaination from model_training.custom_datasets.translation import WMT2019, DiveMT, TEDTalk from sklearn.model_selection import train_test_split from torch.utils.data import Dataset, Subset QA_DATASETS = list(QADataset.D...
@@ -45,13 +46,7 @@ "oa_translated", ] -RL_DATASETS = [ - "webgpt", - "private_tuning", - "alpaca", - "hf_summary", - "hf_summary_pairs", -] +RL_DATASETS = ["webgpt", "private_tuning", "alpaca", "hf_summary", "hf_summary_pairs", "vicuna"]
model/model_training/custom_datasets/__init__.py
26
Python
0.286
suggestion
53
51
51
false
Add vicuna dataset
2,364
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
CloseChoice
Review this pull request change. Language: Python File: model/model_training/custom_datasets/__init__.py PR Title: Add vicuna dataset BEFORE CODE: from model_training.custom_datasets.toxic_conversation import ProsocialDialogue, ProsocialDialogueExplaination from model_training.custom_datasets.translation import WMT...
please use ',' at the end to have one entry per line.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { useChatContext } from "./ChatContext"; import { ChatConversation } from "./ChatConversation"; const CHAT_CONFIG_KEY = "CHAT_CONFIG"; export const ChatSection = ({ chatId }: { chatId: string }) => { const { modelInfos } = useChatContext(); const oldConfig = localStorage.getItem(CHAT_CONFIG_KEY); consol...
can use extract this to an empty component? watching on root component causes a lot rerender. You result the form context, so no need to pass any props.
import { useChatContext } from "./ChatContext"; import { ChatConversation } from "./ChatConversation"; export const ChatSection = ({ chatId }: { chatId: string }) => { const { modelInfos } = useChatContext(); console.assert(modelInfos.length > 0, "No model config was found"); const form = useForm<ChatConfigForm...
@@ -1,21 +1,35 @@ +import { useEffect } from "react"; import { FormProvider, useForm } from "react-hook-form"; import { ChatConfigForm } from "src/types/Chat"; import { ChatConfigSummary } from "./ChatConfigSummary"; import { useChatContext } from "./ChatContext"; import { ChatConversation } from "./ChatConversa...
website/src/components/Chat/ChatSection.tsx
26
TypeScript
0.429
refactor
152
35
26
false
Persist chat config
2,367
LAION-AI/Open-Assistant
29,137
Python
notmd
AbdBarho
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatSection.tsx PR Title: Persist chat config BEFORE CODE: import { useChatContext } from "./ChatContext"; import { ChatConversation } from "./ChatConversation"; const CHAT_CONFIG_KEY = "CHAT_CONFIG"; export const ChatSection ...
can use extract this to an empty component? watching on root component causes a lot rerender. You result the form context, so no need to pass any props.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { useEffect } from "react"; import { FormProvider, useForm } from "react-hook-form"; import { ChatConfigForm } from "src/types/Chat"; import { ChatConfigSummary } from "./ChatConfigSummary"; import { useChatContext } from "./ChatContext"; import { ChatConversation } from "./ChatConversation"; const CHAT_CONFIG...
Isn't this crash on the server side?
import { FormProvider, useForm } from "react-hook-form"; import { getCachedChatForm, useCacheChatForm } from "src/hooks/chat/useCacheConfig"; import { ChatConfigForm } from "src/types/Chat"; import { ChatConfigSummary } from "./ChatConfigSummary"; import { useChatContext } from "./ChatContext"; import { ChatConversati...
@@ -1,21 +1,35 @@ +import { useEffect } from "react"; import { FormProvider, useForm } from "react-hook-form"; import { ChatConfigForm } from "src/types/Chat"; import { ChatConfigSummary } from "./ChatConfigSummary"; import { useChatContext } from "./ChatContext"; import { ChatConversation } from "./ChatConversa...
website/src/components/Chat/ChatSection.tsx
14
TypeScript
0.071
bug
36
39
31
false
Persist chat config
2,367
LAION-AI/Open-Assistant
29,137
Python
notmd
AbdBarho
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatSection.tsx PR Title: Persist chat config BEFORE CODE: import { useEffect } from "react"; import { FormProvider, useForm } from "react-hook-form"; import { ChatConfigForm } from "src/types/Chat"; import { ChatConfigSummary ...
Isn't this crash on the server side?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { getValidDisplayName } from "src/lib/display_name_validation"; import { userlessApiClient } from "src/lib/oasst_client_factory"; import prisma from "src/lib/prismadb"; import { getFrontendUserIdForDiscordUser } from "src/lib/users"; import { LeaderboardEntity, LeaderboardTimeFrame } from "src/types/Leaderboard"...
fix a bug we already have now: if you go to the prod deployment / admin / open a user that is logged in with discord, the stats are missing at the bottom.
import { getValidDisplayName } from "src/lib/display_name_validation"; import { userlessApiClient } from "src/lib/oasst_client_factory"; import prisma from "src/lib/prismadb"; import { getFrontendUserIdForUser } from "src/lib/users"; import { LeaderboardEntity, LeaderboardTimeFrame } from "src/types/Leaderboard"; impor...
@@ -51,7 +52,8 @@ const ManageUser = ({ user }: InferGetServerSidePropsType<typeof getServerSidePr const toast = useToast(); const { data: stats } = uswSWRImmutable<Partial<{ [time in LeaderboardTimeFrame]: LeaderboardEntity }>>( - "/api/user_stats?uid=" + user.id, + "/api/user_stats?" + + new URLSea...
website/src/pages/admin/manage_user/[id].tsx
26
TypeScript
0.571
bug
158
51
51
false
Google auth website
2,391
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
AbdBarho
Review this pull request change. Language: TypeScript File: website/src/pages/admin/manage_user/[id].tsx PR Title: Google auth website BEFORE CODE: import { getValidDisplayName } from "src/lib/display_name_validation"; import { userlessApiClient } from "src/lib/oasst_client_factory"; import prisma from "src/lib/pri...
fix a bug we already have now: if you go to the prod deployment / admin / open a user that is logged in with discord, the stats are missing at the bottom.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
try: response = await call_next(request) except Exception: logger.exception("Exception in request") raise return response pipeline_loaded: bool = False pipeline: Blade2Blade @app.on_event("startup") async def load_pipeline(): global pipeline_loaded, pipeline pipeline = Bl...
can we make this into a `while` with `asyncio.sleep`? or perhaps the question would be, how long does it take to init? 1 second? 1 minute?
pipeline_loaded: bool = False pipeline: Blade2Blade executor = ThreadPoolExecutor() @app.on_event("startup") async def load_pipeline(): global pipeline_loaded, pipeline pipeline = Blade2Blade(settings.safety_model_name) # warmup input = "|prompter|Hey,how are you?|endoftext|" _ = pipeline.predict(...
@@ -0,0 +1,65 @@ +# A FastAPI server to run the safety pipeline + +import fastapi +import uvicorn +from blade2blade import Blade2Blade +from fastapi.middleware.cors import CORSMiddleware +from loguru import logger +from oasst_shared.schemas import inference +from settings import settings + +app = fastapi.FastAPI() + + ...
inference/safety/main.py
26
Python
0.5
question
138
41
39
false
Add safety server to inference
2,449
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
olliestanley
Review this pull request change. Language: Python File: inference/safety/main.py PR Title: Add safety server to inference BEFORE CODE: try: response = await call_next(request) except Exception: logger.exception("Exception in request") raise return response pipeline_loaded: bool...
can we make this into a `while` with `asyncio.sleep`? or perhaps the question would be, how long does it take to init? 1 second? 1 minute?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
class InternalFinishedMessageResponse(WorkerResponseBase): response_type: Literal["internal_finished_message"] = "internal_finished_message" message: MessageRead class InternalErrorResponse(WorkerResponseBase): response_type: Literal["internal_error"] = "internal_error" error: str message: Messag...
what does `...` mean in this context, is this the same as `pass`? I am not a python guru so bare with me on this one
class PongResponse(WorkerResponseBase): response_type: Literal["pong"] = "pong" metrics: WorkerMetricsInfo | None = None class TokenResponse(WorkerResponseBase): response_type: Literal["token"] = "token" text: str log_prob: float | None token_id: int class GeneratedTextResponse(WorkerRespo...
@@ -256,6 +256,19 @@ class GeneralErrorResponse(WorkerResponseBase): error: str +class SafetyParameters(pydantic.BaseModel): + ...
oasst-shared/oasst_shared/schemas/inference.py
26
Python
0.5
question
119
51
51
false
Add safety server to inference
2,449
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
olliestanley
Review this pull request change. Language: Python File: oasst-shared/oasst_shared/schemas/inference.py PR Title: Add safety server to inference BEFORE CODE: class InternalFinishedMessageResponse(WorkerResponseBase): response_type: Literal["internal_finished_message"] = "internal_finished_message" message: ...
what does `...` mean in this context, is this the same as `pass`? I am not a python guru so bare with me on this one
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# A FastAPI server to run the safety pipeline import fastapi import uvicorn from blade2blade import Blade2Blade from fastapi.middleware.cors import CORSMiddleware from loguru import logger from oasst_shared.schemas import inference from settings import settings app = fastapi.FastAPI() # Allow CORS app.add_middlewar...
this is probably not needed, since no browser will try to reach this directly, right?
# A FastAPI server to run the safety pipeline import asyncio from concurrent.futures import ThreadPoolExecutor import fastapi import uvicorn from blade2blade import Blade2Blade from loguru import logger from oasst_shared.schemas import inference from settings import settings app = fastapi.FastAPI() @app.middleware...
@@ -0,0 +1,65 @@ +# A FastAPI server to run the safety pipeline + +import fastapi +import uvicorn +from blade2blade import Blade2Blade +from fastapi.middleware.cors import CORSMiddleware +from loguru import logger +from oasst_shared.schemas import inference +from settings import settings + +app = fastapi.FastAPI() + + ...
inference/safety/main.py
21
Python
0.214
question
85
46
46
false
Add safety server to inference
2,449
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
olliestanley
Review this pull request change. Language: Python File: inference/safety/main.py PR Title: Add safety server to inference BEFORE CODE: # A FastAPI server to run the safety pipeline import fastapi import uvicorn from blade2blade import Blade2Blade from fastapi.middleware.cors import CORSMiddleware from loguru impor...
this is probably not needed, since no browser will try to reach this directly, right?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
logger.exception("Exception in request") raise return response pipeline_loaded: bool = False pipeline: Blade2Blade @app.on_event("startup") async def load_pipeline(): global pipeline_loaded, pipeline pipeline = Blade2Blade(settings.safety_model_name) # warmup input = "|prompter|H...
how does the parallelism of this look like? does the async make it absolutely single-threaded/event-looped?
except Exception: logger.exception("Exception in request") raise return response pipeline_loaded: bool = False pipeline: Blade2Blade executor = ThreadPoolExecutor() @app.on_event("startup") async def load_pipeline(): global pipeline_loaded, pipeline pipeline = Blade2Blade(settings.sa...
@@ -0,0 +1,57 @@ +# A FastAPI server to run the safety pipeline + +import asyncio + +import fastapi +import uvicorn +from blade2blade import Blade2Blade +from loguru import logger +from oasst_shared.schemas import inference +from settings import settings + +app = fastapi.FastAPI() + + +@app.middleware("http") +async de...
inference/safety/main.py
26
Python
0.5
question
107
39
45
false
Add safety server to inference
2,449
LAION-AI/Open-Assistant
29,137
Python
yk
olliestanley
Review this pull request change. Language: Python File: inference/safety/main.py PR Title: Add safety server to inference BEFORE CODE: logger.exception("Exception in request") raise return response pipeline_loaded: bool = False pipeline: Blade2Blade @app.on_event("startup") async def load_pi...
how does the parallelism of this look like? does the async make it absolutely single-threaded/event-looped?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# construct prompt messages = [_prepare_message(message) for message in work_request.thread.messages] prompt = "".join(messages) + V2_ASST_PREFIX parameters = interface.GenerateStreamParameters.from_work_parameters(work_request.parameters) if settings.use_stop_sequences: parameters.stop = ...
we definitely need to track when this happens and feed it back in the response to the backend, and then to the user
# construct prompt messages = [_prepare_message(message) for message in work_request.thread.messages] prompt = "".join(messages) + V2_ASST_PREFIX parameters = interface.GenerateStreamParameters.from_work_parameters(work_request.parameters) if settings.use_stop_sequences: parameters.stop = ...
@@ -79,6 +80,18 @@ def _prepare_message(message: inference.MessageRead) -> str: return prompt, parameters +def prepare_safe_prompt(prompt: str, safety_opinion: str): + safety_opinion = re.sub(r"<pad>|</s>", "", safety_opinion).split("<sep>") + label, rots = safety_opinion[0], "and".join([x.strip(".") for...
inference/worker/work.py
26
Python
0.429
suggestion
115
51
51
false
Add safety server to inference
2,449
LAION-AI/Open-Assistant
29,137
Python
yk
olliestanley
Review this pull request change. Language: Python File: inference/worker/work.py PR Title: Add safety server to inference BEFORE CODE: # construct prompt messages = [_prepare_message(message) for message in work_request.thread.messages] prompt = "".join(messages) + V2_ASST_PREFIX parameters = inte...
we definitely need to track when this happens and feed it back in the response to the backend, and then to the user
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
timeout = "timeout" class MessageRead(pydantic.BaseModel): id: str parent_id: str | None content: str | None created_at: datetime role: Literal["prompter", "assistant"] state: MessageState score: int reports: list[Report] = [] # work parameters will be None on user prompts ...
would set to `False` by default bc if this gets merged & released without the safety server being up yet, we want it to be "backwards compatible"
timeout = "timeout" class MessageRead(pydantic.BaseModel): id: str parent_id: str | None content: str | None created_at: datetime role: Literal["prompter", "assistant"] state: MessageState score: int reports: list[Report] = [] # work parameters will be None on user prompts ...
@@ -178,6 +178,19 @@ class Thread(pydantic.BaseModel): messages: list[MessageRead] +class SafetyParameters(pydantic.BaseModel): + enabled: bool = True
oasst-shared/oasst_shared/schemas/inference.py
26
Python
0.5
suggestion
145
51
51
false
Add safety server to inference
2,449
LAION-AI/Open-Assistant
29,137
Python
yk
olliestanley
Review this pull request change. Language: Python File: oasst-shared/oasst_shared/schemas/inference.py PR Title: Add safety server to inference BEFORE CODE: timeout = "timeout" class MessageRead(pydantic.BaseModel): id: str parent_id: str | None content: str | None created_at: datetime rol...
would set to `False` by default bc if this gets merged & released without the safety server being up yet, we want it to be "backwards compatible"
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
user.tos_acceptance_date = utcnow() self.db.add(user) return user @managed_tx_method(CommitMode.COMMIT) def mark_user_deleted(self, id: UUID) -> None: """ Update a user by global user ID to set deleted flag. Only trusted clients may delete users. User deleti...
I see the intention is it to keep this info coherent for inference and backend user data. like it is used in inference/server/oasst_inference_server/routes/admin.py as well. Can this be defined in oasst-shared/utils.py. ? example ` DELETED_USER = "Deleted User" ` `user.display_name = utils.DELETED_USER` Simil...
if tos_acceptance: user.tos_acceptance_date = utcnow() self.db.add(user) return user @managed_tx_method(CommitMode.COMMIT) def mark_user_deleted(self, id: UUID) -> None: """ Update a user by global user ID to set deleted flag. Only trusted clients may delete...
@@ -119,6 +120,12 @@ def mark_user_deleted(self, id: UUID) -> None: user.deleted = True + # Anonymise user data + user.display_name = "Deleted User"
backend/oasst_backend/user_repository.py
26
Python
0.643
suggestion
424
51
51
false
Add support for user deletion
2,486
LAION-AI/Open-Assistant
29,137
Python
melvinebenezer
olliestanley
Review this pull request change. Language: Python File: backend/oasst_backend/user_repository.py PR Title: Add support for user deletion BEFORE CODE: user.tos_acceptance_date = utcnow() self.db.add(user) return user @managed_tx_method(CommitMode.COMMIT) def mark_user_deleted(se...
I see the intention is it to keep this info coherent for inference and backend user data. like it is used in inference/server/oasst_inference_server/routes/admin.py as well. Can this be defined in oasst-shared/utils.py. ? example ` DELETED_USER = "Deleted User" ` `user.display_name = utils.DELETED_USER` Simil...
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
} setQueueInfo(null); setResponse(null); setIsSending.off(); }, [getFormValues, setIsSending] ); const sendPrompterMessage = useCallback(async () => { const content = inputRef.current?.value.trim(); if (!content) { return; } setIsSending.on(); // find last ...
To prevent refresh, we simply can check whether the chatIdProps is null or not here.
const parent = messages.find((m) => m.id === parentId); if (!parent) { // we should never reach here return console.error("Parent message not found", parentId); } if (parent!.state !== "complete") { return toast({ title: "You are trying reply to a message that i...
@@ -119,27 +111,28 @@ export const ChatConversation = memo(function ChatConversation({ chatId: chatIdP .find((m) => m.role === "assistant" && m.state === "complete")?.id ?? null; const prompter_arg: InferencePostPrompterMessageParams = { - chat_id: currentChatId, + chat_id: chatId, cont...
website/src/components/Chat/ChatConversation.tsx
26
TypeScript
0.357
suggestion
84
51
51
false
Don't refresh the page after each message
2,491
LAION-AI/Open-Assistant
29,137
Python
notmd
AbdBarho
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatConversation.tsx PR Title: Don't refresh the page after each message BEFORE CODE: } setQueueInfo(null); setResponse(null); setIsSending.off(); }, [getFormValues, setIsSending] ); const sen...
To prevent refresh, we simply can check whether the chatIdProps is null or not here.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
return prepare_safe_prompt(prompt, label, rots) elif "intervention" in label and safety_level > 0: return prepare_safe_prompt(prompt, label, rots) else: return prompt def handle_work_request( ws: websocket.WebSocket, tokenizer: transformers.PreTrainedTokenizer, work_request...
could we get as much as possible of the safety response in here? like what was the detected intervention level?
label, rots = safety_opinion[0], "and".join([x.strip(".") for x in safety_opinion[1:]]) label = label.replace("<pad>", "").strip() return label, rots def handle_work_request( ws: websocket.WebSocket, tokenizer: transformers.PreTrainedTokenizer, work_request: inference.WorkRequest, worker_c...
@@ -115,7 +115,18 @@ def handle_work_request( if settings.enable_safety and work_request.safety_parameters.level: safety_request = inference.SafetyRequest(inputs=prompt, parameters=work_request.safety_parameters) safety_response = get_safety_server_response(safety_request) - prompt = get_s...
inference/worker/work.py
26
Python
0.429
question
111
51
51
false
Inference worker inform backend on safety intervention
2,505
LAION-AI/Open-Assistant
29,137
Python
yk
olliestanley
Review this pull request change. Language: Python File: inference/worker/work.py PR Title: Inference worker inform backend on safety intervention BEFORE CODE: return prepare_safe_prompt(prompt, label, rots) elif "intervention" in label and safety_level > 0: return prepare_safe_prompt(prompt, lab...
could we get as much as possible of the safety response in here? like what was the detected intervention level?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
mutateChats( (chatResponse) => ({ ...chatResponse, chats: chatResponse?.chats.map((chat) => (chat.id === chatId ? { ...chat, title } : chat)) || [], }), false ); }, [mutateChats] ); return ( <Card w="260px" py="3" gap="1" h...
is this necessary? I assume we update the title in the `ChatItem`, and then we just refresh here? do we need to re-assign the title here again?.
{ fallbackData: chats, } ); const { t } = useTranslation(["common", "chat"]); const sideProps: CardProps = useMemo( () => isSideBar ? { w: "260px", position: "fixed", } : {}, [isSideBar] ); const handleUpdateTitle = useCallback( ...
@@ -15,11 +15,24 @@ import { HEADER_HEIGHT } from "../Header/Header"; import { ChatListItem } from "./ChatListItem"; export const ChatListBase = memo(function ChatListBase(props: CardProps) { - const { data: chats } = useSWR<GetChatsResponse>(API_ROUTES.LIST_CHAT, get, { + const { data: chats, mutate: mutateChats...
website/src/components/Chat/ChatListBase.tsx
26
TypeScript
0.5
question
144
51
51
false
implement update chat title UI
2,507
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
notmd
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatListBase.tsx PR Title: implement update chat title UI BEFORE CODE: mutateChats( (chatResponse) => ({ ...chatResponse, chats: chatResponse?.chats.map((chat) => (chat.id === chatId ? { ...chat...
is this necessary? I assume we update the title in the `ChatItem`, and then we just refresh here? do we need to re-assign the title here again?.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
); const handleConfirmEdit = useCallback(async () => { const title = inputRef.current?.value; if (!title) return; await updateChatTitle({ title, chat_id: chat.id }); setIsEditing.off(); onUpdateTitle({ chatId: chat.id, title }); }, [chat.id, onUpdateTitle, setIsEditing, updateChatTitle]); c...
Does this work? keep it as `Link` & remove the href when editing (or set to '#'), then it would not navigate. Assuming that was the problem.
); const handleConfirmEdit = useCallback(async () => { const title = inputRef.current?.value.trim(); if (!title) return; await updateChatTitle({ title, chat_id: chat.id }); setIsEditing.off(); onUpdateTitle({ chatId: chat.id, title }); }, [chat.id, onUpdateTitle, setIsEditing, updateChatTitle]...
@@ -1,41 +1,119 @@ -import { Box, Button, Flex, Tooltip, useToast } from "@chakra-ui/react"; -import { LucideIcon, Pencil, Trash2 } from "lucide-react"; +import { Box, Button, CircularProgress, Flex, Input, Tooltip, useBoolean, useOutsideClick } from "@chakra-ui/react"; +import { Check, LucideIcon, Pencil, Trash2, X } ...
website/src/components/Chat/ChatListItem.tsx
26
TypeScript
0.571
question
140
51
51
false
implement update chat title UI
2,507
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
notmd
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatListItem.tsx PR Title: implement update chat title UI BEFORE CODE: ); const handleConfirmEdit = useCallback(async () => { const title = inputRef.current?.value; if (!title) return; await updateChatTitle({ tit...
Does this work? keep it as `Link` & remove the href when editing (or set to '#'), then it would not navigate. Assuming that was the problem.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
max_new_tokens: 256, repetition_penalty: 1.2, temperature: 1, top_k: 50, top_p: 0.95, typical_p: 0.5, }; const parameterLabel: Record<keyof SamplingParameters, string> = { max_new_tokens: "Max new tokens", top_k: "Top K", top_p: "Top P", temperature: "Temperature", repetition_penalty: "Repetition...
should `presets[0].name` be `customPresetName`?
max_new_tokens: 256, repetition_penalty: 1.2, temperature: 1, top_k: 50, top_p: 0.95, typical_p: 0.5, }; const parameterLabel: Record<keyof SamplingParameters, string> = { max_new_tokens: "Max new tokens", top_k: "Top K", top_p: "Top P", temperature: "Temperature", repetition_penalty: "Repetition...
@@ -118,7 +118,9 @@ const ChatConfigForm = () => { const { control, register, reset, getValues } = useFormContext<ChatConfigFormData>(); const selectedModel = useWatch({ name: "model_config_name", control: control }); const presets = modelInfos.find((model) => model.name === selectedModel)!.parameter_configs; ...
website/src/components/Chat/ChatConfigDrawer.tsx
26
TypeScript
0.286
question
47
51
51
false
fix custom preset selection
2,511
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
notmd
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatConfigDrawer.tsx PR Title: fix custom preset selection BEFORE CODE: max_new_tokens: 256, repetition_penalty: 1.2, temperature: 1, top_k: 50, top_p: 0.95, typical_p: 0.5, }; const parameterLabel: Record<keyof Sam...
should `presets[0].name` be `customPresetName`?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
return fastapi.Response(status_code=200) except Exception: logger.exception("Error adding report") return fastapi.Response(status_code=500) @router.put("/{chat_id}/title") async def handle_update_title( chat_id: str, request: chat_schema.ChatUpdateTitleRequest, ucr: deps.UserCh...
can we make this a toggle? i.e. hide / unhide, either as a boolean parameter (default hidden) or simply inverting whatever is the database. Motivation: users would expect the ability to make stuff visible again, unlike delete, which is gone permanently.
return fastapi.Response(status_code=200) except Exception: logger.exception("Error adding report") return fastapi.Response(status_code=500) @router.put("/{chat_id}/title") async def handle_update_title( chat_id: str, request: chat_schema.ChatUpdateTitleRequest, ucr: deps.UserCh...
@@ -270,3 +271,12 @@ async def handle_update_title( except Exception: logger.exception("Error when updating chat title") return fastapi.Response(status_code=500) + + +@router.put("/{chat_id}/hide") +async def hide_chat( + chat_id: str, + ucr: UserChatRepository = Depends(deps.create_user_ch...
inference/server/oasst_inference_server/routes/chats.py
26
Python
0.5
question
258
28
29
false
Add ability to hide (soft delete) chats to inference backend
2,512
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
olliestanley
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/routes/chats.py PR Title: Add ability to hide (soft delete) chats to inference backend BEFORE CODE: return fastapi.Response(status_code=200) except Exception: logger.exception("Error adding report") ...
can we make this a toggle? i.e. hide / unhide, either as a boolean parameter (default hidden) or simply inverting whatever is the database. Motivation: users would expect the ability to make stuff visible again, unlike delete, which is gone permanently.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
id=self.id, parent_id=self.parent_id, chat_id=self.chat_id, content=self.content, created_at=self.created_at, role=self.role, state=self.state, score=self.score, work_parameters=self.work_parameters, ...
quick question: what is the motivation of making it an index? is there a situation where we can have the same id but once visible once not? or is it just about speeding up the queries?
id=self.id, parent_id=self.parent_id, chat_id=self.chat_id, content=self.content, created_at=self.created_at, role=self.role, state=self.state, score=self.score, work_parameters=self.work_parameters, ...
@@ -74,12 +74,15 @@ class DbChat(SQLModel, table=True): messages: list[DbMessage] = Relationship(back_populates="chat") + hidden: bool = Field(False, index=True)
inference/server/oasst_inference_server/models/chat.py
26
Python
0.357
question
187
51
51
false
Add ability to hide (soft delete) chats to inference backend
2,512
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
olliestanley
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/models/chat.py PR Title: Add ability to hide (soft delete) chats to inference backend BEFORE CODE: id=self.id, parent_id=self.parent_id, chat_id=self.chat_id, content=self....
quick question: what is the motivation of making it an index? is there a situation where we can have the same id but once visible once not? or is it just about speeding up the queries?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
label = label.replace("<pad>", "").strip() if "caution" in label and safety_level > 1: return prepare_safe_prompt(prompt, label, rots) elif "intervention" in label and safety_level > 0: return prepare_safe_prompt(prompt, label, rots) else: return prompt def handle_work_request...
We are already receiving a desired safety level from the backend (which in turn comes from the frontend as a user setting) as part of the `SafetyParameters` in the work request. So we can remove the `safety_level` setting from `settings.py` and this line can become: `prompt = get_safety_opinion(prompt, safety_respon...
label = label.replace("<pad>", "").strip() if "caution" in label and safety_level > 1: return prepare_safe_prompt(prompt, label, rots) elif "intervention" in label and safety_level > 0: return prepare_safe_prompt(prompt, label, rots) else: return prompt def handle_work_request...
@@ -107,7 +115,7 @@ def handle_work_request( if settings.enable_safety and work_request.safety_parameters.level: safety_request = inference.SafetyRequest(inputs=prompt, parameters=work_request.safety_parameters) safety_response = get_safety_server_response(safety_request) - prompt = prepar...
inference/worker/work.py
26
Python
0.643
suggestion
370
51
51
false
Safety level control
2,516
LAION-AI/Open-Assistant
29,137
Python
olliestanley
shahules786
Review this pull request change. Language: Python File: inference/worker/work.py PR Title: Safety level control BEFORE CODE: label = label.replace("<pad>", "").strip() if "caution" in label and safety_level > 1: return prepare_safe_prompt(prompt, label, rots) elif "intervention" in label and sa...
We are already receiving a desired safety level from the backend (which in turn comes from the frontend as a user setting) as part of the `SafetyParameters` in the work request. So we can remove the `safety_level` setting from `settings.py` and this line can become: `prompt = get_safety_opinion(prompt, safety_respon...
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
CV = "cv" # Chuvash KW = "kw" # Cornish CO = "co" # Corsican CR = "cr" # Cree HR = "hr" # Croatian CS = "cs" # Czech DA = "da" # Danish DV = "dv" # Divehi, Dhivehi, Maldivian NL = "nl" # Dutch, Flemish DZ = "dz" # Dzongkha EN = "en" # English EO = "eo" # Esper...
Does this mean that RM training will not work after this is merged?
return f"{system_tag}{QA_SPECIAL_TOKENS['Question']}{self.questions[0]}{QA_SPECIAL_TOKENS['Answer']}" else: return f"{QA_SPECIAL_TOKENS['Question']}{self.questions[0]}{QA_SPECIAL_TOKENS['Answer']}" if system_tag is not None: qa_list = [system_tag] ...
@@ -15,20 +28,291 @@ def format_system_prefix(prefix, eos_token): ) -def format_pairs(pairs, eos_token, add_initial_reply_token=False): - conversations = [ - "{}{}{}".format(QA_SPECIAL_TOKENS["Question" if i % 2 == 0 else "Answer"], pairs[i], eos_token) - for i in range(len(pairs)) - ] - ...
model/model_training/custom_datasets/formatting.py
26
Python
0.214
question
67
51
51
false
Feature/dataset entry
2,520
LAION-AI/Open-Assistant
29,137
Python
dvruette
CloseChoice
Review this pull request change. Language: Python File: model/model_training/custom_datasets/formatting.py PR Title: Feature/dataset entry BEFORE CODE: CV = "cv" # Chuvash KW = "kw" # Cornish CO = "co" # Corsican CR = "cr" # Cree HR = "hr" # Croatian CS = "cs" # Czech DA = "da" # ...
Does this mean that RM training will not work after this is merged?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
@unique class Language(str, Enum): AB = "ab" # Abkhazian AA = "aa" # Afar AF = "af" # Afrikaans AK = "ak" # Akan SQ = "sq" # Albanian AM = "am" # Amharic AR = "ar" # Arabic AN = "an" # Aragonese HY = "hy" # Armenian AS = "as" # Assamese AV = "av" # Avaric AE =...
Should the values be quantized here or are they already within a certain set? (I think real values could be difficult to understand for the model)
length: int | None quality: float | None humor: float | None creativity: float | None @validator("length") def above_zero(cls, v) -> int: if v is not None and v < 0: raise ValueError(f"Length cannot be lower than 0. Received {v}") return v @validator("quality", ...
@@ -15,20 +28,291 @@ def format_system_prefix(prefix, eos_token): ) -def format_pairs(pairs, eos_token, add_initial_reply_token=False): - conversations = [ - "{}{}{}".format(QA_SPECIAL_TOKENS["Question" if i % 2 == 0 else "Answer"], pairs[i], eos_token) - for i in range(len(pairs)) - ] - ...
model/model_training/custom_datasets/formatting.py
26
Python
0.429
suggestion
146
51
51
false
Feature/dataset entry
2,520
LAION-AI/Open-Assistant
29,137
Python
dvruette
CloseChoice
Review this pull request change. Language: Python File: model/model_training/custom_datasets/formatting.py PR Title: Feature/dataset entry BEFORE CODE: @unique class Language(str, Enum): AB = "ab" # Abkhazian AA = "aa" # Afar AF = "af" # Afrikaans AK = "ak" # Akan SQ = "sq" # Albanian ...
Should the values be quantized here or are they already within a certain set? (I think real values could be difficult to understand for the model)
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
QA_SPECIAL_TOKENS = { "Question": "<|prompter|>", "Answer": "<|assistant|>", "System": "<|system|>", "StartPrefix": "<|prefix_begin|>", "EndPrefix": "<|prefix_end|>", } class Mode(Enum): sft = "sft" rm = "rm" rl = "rl" def format_system_prefix(prefix, eos_token): return "{}{}{}"...
worth considering extracting this class into a separate file. not necessary, i'll leave it up to you
QA_SPECIAL_TOKENS = { "Question": "<|prompter|>", "Answer": "<|assistant|>", "System": "<|system|>", "StartPrefix": "<|prefix_begin|>", "EndPrefix": "<|prefix_end|>", } def format_system_prefix(prefix, eos_token): return "{}{}{}".format( QA_SPECIAL_TOKENS["System"], prefix, ...
@@ -15,20 +28,291 @@ def format_system_prefix(prefix, eos_token): ) -def format_pairs(pairs, eos_token, add_initial_reply_token=False): - conversations = [ - "{}{}{}".format(QA_SPECIAL_TOKENS["Question" if i % 2 == 0 else "Answer"], pairs[i], eos_token) - for i in range(len(pairs)) - ] - ...
model/model_training/custom_datasets/formatting.py
26
Python
0.429
refactor
100
51
51
false
Feature/dataset entry
2,520
LAION-AI/Open-Assistant
29,137
Python
dvruette
CloseChoice
Review this pull request change. Language: Python File: model/model_training/custom_datasets/formatting.py PR Title: Feature/dataset entry BEFORE CODE: QA_SPECIAL_TOKENS = { "Question": "<|prompter|>", "Answer": "<|assistant|>", "System": "<|system|>", "StartPrefix": "<|prefix_begin|>", "EndPre...
worth considering extracting this class into a separate file. not necessary, i'll leave it up to you
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
from loguru import logger from oasst_inference_server import database, models from oasst_shared import utils as shared_utils async def delete_user_from_db(session: database.AsyncSession, user_id: str) -> bool: """Deletes a user.""" logger.info(f"Deleting user {user_id}") user = await session.get(models.Db...
I think we should just raise an exception (404) on fail here instead of returning `bool`, that's more in line with the rest of the codebase
import fastapi from loguru import logger from oasst_inference_server import database, models from oasst_shared import utils as shared_utils async def delete_user_from_db(session: database.AsyncSession, user_id: str): """Deletes a user.""" logger.info(f"Deleting user {user_id}") user = await session.get(mo...
@@ -0,0 +1,20 @@ +from loguru import logger +from oasst_inference_server import database, models +from oasst_shared import utils as shared_utils + + +async def delete_user_from_db(session: database.AsyncSession, user_id: str) -> bool: + """Deletes a user.""" + logger.info(f"Deleting user {user_id}") + user = a...
inference/server/oasst_inference_server/admin.py
11
Python
0.714
bug
139
21
24
false
Add delete account page
2,523
LAION-AI/Open-Assistant
29,137
Python
olliestanley
AbdBarho
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/admin.py PR Title: Add delete account page BEFORE CODE: from loguru import logger from oasst_inference_server import database, models from oasst_shared import utils as shared_utils async def delete_user_from_db(session...
I think we should just raise an exception (404) on fail here instead of returning `bool`, that's more in line with the rest of the codebase
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
if (req.method !== "DELETE") { return res.status(400).end(); } console.log("deleting user", token.sub); try { const backendUserCore = await getBackendUserCore(token.sub); const client = createApiClientFromUser(backendUserCore); await client.delete_account(backendUserCore); console.log(`user...
I think we need to setup the logger for frontend soon, since console.log is blocking the cpu
if (req.method !== "DELETE") { return res.status(400).end(); } console.log("deleting user", token.sub); try { const backendUserCore = await getBackendUserCore(token.sub); const client = createApiClientFromUser(backendUserCore); await client.delete_account(backendUserCore); console.log(`user...
@@ -0,0 +1,55 @@ +import { AxiosError } from "axios"; +import type { NextApiRequest, NextApiResponse } from "next"; +import { getToken } from "next-auth/jwt"; +import { createApiClientFromUser } from "src/lib/oasst_client_factory"; +import { createInferenceClient } from "src/lib/oasst_inference_client"; +import prisma ...
website/src/pages/api/account/delete.ts
26
TypeScript
0.214
suggestion
92
42
42
false
Add delete account page
2,523
LAION-AI/Open-Assistant
29,137
Python
notmd
AbdBarho
Review this pull request change. Language: TypeScript File: website/src/pages/api/account/delete.ts PR Title: Add delete account page BEFORE CODE: if (req.method !== "DELETE") { return res.status(400).end(); } console.log("deleting user", token.sub); try { const backendUserCore = await getBackendUs...
I think we need to setup the logger for frontend soon, since console.log is blocking the cpu
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
cache_dir=cache_dir, data_files=["ShareGPT_V3_unfiltered_cleaned_split.json"], revision="192ab2185289094fc556ec8ce5ce1e8e587154ca", )["train"] for data in dataset: if ( processed_data := self.process_vicuna_conversations(data, input_max_len...
could we please also use the same regex that is defined here: https://github.com/LAION-AI/Open-Assistant/blob/2e6f22c2a137ee60ef68cf908073c1e29babd633/model/model_training/custom_datasets/qa_datasets.py#L20 maybe also add upper case single latter references?
cache_dir=cache_dir, data_files=["ShareGPT_V3_unfiltered_cleaned_split.json"], revision="192ab2185289094fc556ec8ce5ce1e8e587154ca", )["train"] for data in dataset: if ( processed_data := self.process_vicuna_conversations(data, input_max_len...
@@ -552,6 +552,7 @@ class DatabricksDolly15k(Dataset): def __init__(self, cache_dir: str | Path, mode: str = "sft", input_max_length: int = 2048) -> None: super().__init__() self.rows = [] + self.citation_regex = re.compile(r"\[[a-z]\]") # removes citations in the form of e.g. [a]
model/model_training/custom_datasets/qa_datasets.py
26
Python
0.5
question
261
51
51
false
remove references from dolly
2,535
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
CloseChoice
Review this pull request change. Language: Python File: model/model_training/custom_datasets/qa_datasets.py PR Title: remove references from dolly BEFORE CODE: cache_dir=cache_dir, data_files=["ShareGPT_V3_unfiltered_cleaned_split.json"], revision="192ab2185289094fc556ec8ce5ce1e8...
could we please also use the same regex that is defined here: https://github.com/LAION-AI/Open-Assistant/blob/2e6f22c2a137ee60ef68cf908073c1e29babd633/model/model_training/custom_datasets/qa_datasets.py#L20 maybe also add upper case single latter references?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
try: await ucr.update_score(message_id=message_id, score=vote_request.score) return fastapi.Response(status_code=200) except Exception: logger.exception("Error adding vote") return fastapi.Response(status_code=500) @router.post("/{chat_id}/messages/{message_id}/reports") async ...
Maybe "/{chat_id/}" is enough?
try: await ucr.update_score(message_id=message_id, score=vote_request.score) return fastapi.Response(status_code=200) except Exception: logger.exception("Error adding vote") return fastapi.Response(status_code=500) @router.post("/{chat_id}/messages/{message_id}/reports") async ...
@@ -259,25 +259,19 @@ async def handle_create_report( return fastapi.Response(status_code=500) -@router.put("/{chat_id}/title") -async def handle_update_title( +@router.put("/{chat_id}/update")
inference/server/oasst_inference_server/routes/chats.py
26
Python
0.071
question
30
42
42
false
Unify title update and visibility update inference endpoints
2,627
LAION-AI/Open-Assistant
29,137
Python
notmd
olliestanley
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/routes/chats.py PR Title: Unify title update and visibility update inference endpoints BEFORE CODE: try: await ucr.update_score(message_id=message_id, score=vote_request.score) return fastapi.Response...
Maybe "/{chat_id/}" is enough?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
if not task.collective: task.done = True self.db.add(task) logger.debug(f"inserting TextLabels for {message_id=}, {text_labels_id=}") model = TextLabels( id=text_labels_id, api_client_id=self.api_client.id, message_id=messa...
send message_id inside send_new_report_message, this would be easier for the mod team to search the DB
if not task.collective: task.done = True self.db.add(task) logger.debug(f"inserting TextLabels for {message_id=}, {text_labels_id=}") model = TextLabels( id=text_labels_id, api_client_id=self.api_client.id, message_id=messa...
@@ -546,6 +547,8 @@ def store_text_labels(self, text_labels: protocol_schema.TextLabels) -> tuple[Te message_id, protocol_schema.EmojiOp.add, protocol_schema.EmojiCode.red_flag ) + discord.send_new_report_message(message=message, label_text=text_labels....
backend/oasst_backend/prompt_repository.py
26
Python
0.357
suggestion
102
51
51
false
send flagged message notification to discord
2,641
LAION-AI/Open-Assistant
29,137
Python
melvinebenezer
notmd
Review this pull request change. Language: Python File: backend/oasst_backend/prompt_repository.py PR Title: send flagged message notification to discord BEFORE CODE: if not task.collective: task.done = True self.db.add(task) logger.debug(f"inserting TextLabels f...
send message_id inside send_new_report_message, this would be easier for the mod team to search the DB
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import requests from loguru import logger from oasst_backend.config import settings from oasst_backend.models.message import Message ROOT_ENDPOINT = "https://discord.com/api/v10" def send_new_report_message( message: Message, label_text: str, ) -> None: if settings.DISCORD_API_KEY is None or settings.DIS...
maybe rename to `maybe_send_discord_report_message`
from uuid import UUID import requests from loguru import logger from oasst_backend.config import settings from oasst_backend.models.message import Message ROOT_ENDPOINT = "https://discord.com/api/v10" def send_new_report_message(message: Message, label_text: str, user_id: UUID) -> None: if settings.DISCORD_API_...
@@ -0,0 +1,45 @@ +import requests +from loguru import logger +from oasst_backend.config import settings +from oasst_backend.models.message import Message + +ROOT_ENDPOINT = "https://discord.com/api/v10" + + +def send_new_report_message(
backend/oasst_backend/utils/discord.py
9
Python
0.429
suggestion
51
34
34
false
send flagged message notification to discord
2,641
LAION-AI/Open-Assistant
29,137
Python
yk
notmd
Review this pull request change. Language: Python File: backend/oasst_backend/utils/discord.py PR Title: send flagged message notification to discord BEFORE CODE: import requests from loguru import logger from oasst_backend.config import settings from oasst_backend.models.message import Message ROOT_ENDPOINT = "ht...
maybe rename to `maybe_send_discord_report_message`
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
throw new Error("User not found"); } const backendUser = convertToBackendUserCore(frontendUser); if (backendUser.auth_method === "discord") { const discordAccount = frontendUser.accounts.find((a) => a.provider === "discord"); discordAvatarRefresh.updateImageIfNeces...
the backend does a lazy upsert so we should be safe. see https://github.com/LAION-AI/Open-Assistant/blob/6ba240f590787b40d56b3d14e19fd38b9488c850/backend/oasst_backend/api/v1/frontend_users.py#L62
if (!frontendUser) { // should never reach here throw new Error("User not found"); } // TODO avoid duplicate logic with the signIn event if (frontendUser.isNew && !frontendUser.name) { // jwt callback is called before signIn event, so we need to assign the ...
@@ -222,9 +227,9 @@ export default function auth(req: NextApiRequest, res: NextApiResponse) { * in the frontend, when the user accepts the tos, we do a full refresh * which means this function will be called again. */ - const { user_id, tos_acceptance_date } = await ...
website/src/pages/api/auth/[...nextauth].ts
26
TypeScript
0.429
suggestion
196
51
51
false
create backend user when generate jwt
2,702
LAION-AI/Open-Assistant
29,137
Python
notmd
notmd
Review this pull request change. Language: TypeScript File: website/src/pages/api/auth/[...nextauth].ts PR Title: create backend user when generate jwt BEFORE CODE: throw new Error("User not found"); } const backendUser = convertToBackendUserCore(frontendUser); if (backendUser.aut...
the backend does a lazy upsert so we should be safe. see https://github.com/LAION-AI/Open-Assistant/blob/6ba240f590787b40d56b3d14e19fd38b9488c850/backend/oasst_backend/api/v1/frontend_users.py#L62
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
}; export default function auth(req: NextApiRequest, res: NextApiResponse) { return NextAuth(req, res, { ...authOptions, callbacks: { ...authOptions.callbacks, /** * When creating a token, fetch the user's role and inject it in the token. * This let's use forward the role to the ses...
we already create a username in line 143?
}, }, }; export default function auth(req: NextApiRequest, res: NextApiResponse) { return NextAuth(req, res, { ...authOptions, callbacks: { ...authOptions.callbacks, /** * When creating a token, fetch the user's role and inject it in the token. * This let's use forward the rol...
@@ -200,6 +200,24 @@ export default function auth(req: NextApiRequest, res: NextApiResponse) { select: { name: true, role: true, isNew: true, accounts: true, id: true }, }); + if (!frontendUser) { + // should never reach here + throw new Error("User not found"); + }...
website/src/pages/api/auth/[...nextauth].ts
26
TypeScript
0.143
question
41
51
51
false
create backend user when generate jwt
2,702
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
notmd
Review this pull request change. Language: TypeScript File: website/src/pages/api/auth/[...nextauth].ts PR Title: create backend user when generate jwt BEFORE CODE: }; export default function auth(req: NextApiRequest, res: NextApiResponse) { return NextAuth(req, res, { ...authOptions, callbacks: { ...
we already create a username in line 143?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import json import os import random import pandas as pd # Read the CSV file into a pandas DataFrame. The CSV file was downloaded from Kaggle, and the source is linked in the README. CURRENT_DIR = os.path.dirname(__file__) # Gets directory path of the current python module df = pd.read_csv(os.path.join(CURRENT_DIR, ...
you can also do something like `df["Title"].apply(lambda x: "".join(x.splitlines()).strip())` but it's fine
import json import os import random import kaggle import pandas as pd # Authenticate the Kaggle API client kaggle.api.authenticate() # Download and extract the dataset to the download_path directory download_path = os.path.join(os.getcwd(), "data", "datasets", "poetry_instruction") kaggle.api.dataset_download_files(...
@@ -0,0 +1,151 @@ +import json +import os +import random + +import pandas as pd + +# Read the CSV file into a pandas DataFrame. The CSV file was downloaded from Kaggle, and the source is linked in the README. + +CURRENT_DIR = os.path.dirname(__file__) # Gets directory path of the current python module +df = pd.read_cs...
data/datasets/poetry_instruction/prepare.py
21
Python
0.5
suggestion
109
46
46
false
add poetry dataset setup
2,730
LAION-AI/Open-Assistant
29,137
Python
sedthh
check3D
Review this pull request change. Language: Python File: data/datasets/poetry_instruction/prepare.py PR Title: add poetry dataset setup BEFORE CODE: import json import os import random import pandas as pd # Read the CSV file into a pandas DataFrame. The CSV file was downloaded from Kaggle, and the source is linked...
you can also do something like `df["Title"].apply(lambda x: "".join(x.splitlines()).strip())` but it's fine
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# Shuffle the rows in the DataFrame. df = df.sample(frac=1) # Split the DataFrame into two DataFrames, one for titling tasks and one for writing tasks. writing_tasks = df.iloc[:num_writing_tasks] titling_tasks = df.iloc[num_writing_tasks:] prepared_data = [] # Loop through the writing tasks and process them. for ind...
you can also do string.format() with "blabla {topic}" like https://www.w3schools.com/python/ref_string_format.asp but this is okay too
# Shuffling the dataset and delegating 5% to titling tasks. # Calculating the number of titling tasks and writing tasks. num_rows = len(df) num_titling_tasks = int(num_rows * 0.05) num_writing_tasks = num_rows - num_titling_tasks # Shuffle the rows in the DataFrame. df = df.sample(frac=1) # Split the DataFrame into ...
@@ -0,0 +1,151 @@ +import json +import os +import random + +import pandas as pd + +# Read the CSV file into a pandas DataFrame. The CSV file was downloaded from Kaggle, and the source is linked in the README. + +CURRENT_DIR = os.path.dirname(__file__) # Gets directory path of the current python module +df = pd.read_cs...
data/datasets/poetry_instruction/prepare.py
26
Python
0.357
suggestion
138
51
51
false
add poetry dataset setup
2,730
LAION-AI/Open-Assistant
29,137
Python
sedthh
check3D
Review this pull request change. Language: Python File: data/datasets/poetry_instruction/prepare.py PR Title: add poetry dataset setup BEFORE CODE: # Shuffle the rows in the DataFrame. df = df.sample(frac=1) # Split the DataFrame into two DataFrames, one for titling tasks and one for writing tasks. writing_tasks =...
you can also do string.format() with "blabla {topic}" like https://www.w3schools.com/python/ref_string_format.asp but this is okay too
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# Shuffle the rows in the DataFrame. df = df.sample(frac=1) # Split the DataFrame into two DataFrames, one for titling tasks and one for writing tasks. writing_tasks = df.iloc[:num_writing_tasks] titling_tasks = df.iloc[num_writing_tasks:] prepared_data = [] # Loop through the writing tasks and process them. for in...
please use `pd.isna(instruction)` or something similar, the "nan" is an artifact from converting NaN (missing/None) to string
] # Shuffling the dataset and delegating 5% to titling tasks. # Calculating the number of titling tasks and writing tasks. num_rows = len(df) num_titling_tasks = int(num_rows * 0.05) num_writing_tasks = num_rows - num_titling_tasks # Shuffle the rows in the DataFrame. df = df.sample(frac=1) # Split the DataFrame int...
@@ -0,0 +1,151 @@ +import json +import os +import random + +import pandas as pd + +# Read the CSV file into a pandas DataFrame. The CSV file was downloaded from Kaggle, and the source is linked in the README. + +CURRENT_DIR = os.path.dirname(__file__) # Gets directory path of the current python module +df = pd.read_cs...
data/datasets/poetry_instruction/prepare.py
26
Python
0.571
suggestion
125
51
51
false
add poetry dataset setup
2,730
LAION-AI/Open-Assistant
29,137
Python
sedthh
check3D
Review this pull request change. Language: Python File: data/datasets/poetry_instruction/prepare.py PR Title: add poetry dataset setup BEFORE CODE: # Shuffle the rows in the DataFrame. df = df.sample(frac=1) # Split the DataFrame into two DataFrames, one for titling tasks and one for writing tasks. writing_tasks ...
please use `pd.isna(instruction)` or something similar, the "nan" is an artifact from converting NaN (missing/None) to string
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import json import os import random import pandas as pd # Read the CSV file into a pandas DataFrame. The CSV file was downloaded from Kaggle, and the source is linked in the README. CURRENT_DIR = os.path.dirname(__file__) # Gets directory path of the current python module df = pd.read_csv(os.path.join(CURRENT_DIR, ...
mabye you can also add a KAGGLE dataset loader to unpack this (I can give you an example code for this)
import json import os import random import kaggle import pandas as pd # Authenticate the Kaggle API client kaggle.api.authenticate() # Download and extract the dataset to the download_path directory download_path = os.path.join(os.getcwd(), "data", "datasets", "poetry_instruction") kaggle.api.dataset_download_files(...
@@ -0,0 +1,151 @@ +import json +import os +import random + +import pandas as pd + +# Read the CSV file into a pandas DataFrame. The CSV file was downloaded from Kaggle, and the source is linked in the README. + +CURRENT_DIR = os.path.dirname(__file__) # Gets directory path of the current python module
data/datasets/poetry_instruction/prepare.py
9
Python
0.357
suggestion
103
34
34
false
add poetry dataset setup
2,730
LAION-AI/Open-Assistant
29,137
Python
sedthh
check3D
Review this pull request change. Language: Python File: data/datasets/poetry_instruction/prepare.py PR Title: add poetry dataset setup BEFORE CODE: import json import os import random import pandas as pd # Read the CSV file into a pandas DataFrame. The CSV file was downloaded from Kaggle, and the source is linked...
mabye you can also add a KAGGLE dataset loader to unpack this (I can give you an example code for this)
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
router = fastapi.APIRouter( prefix="/chats", tags=["chats"], ) @router.get("") async def list_chats( include_hidden: bool = False, ucr: UserChatRepository = Depends(deps.create_user_chat_repository), ) -> chat_schema.ListChatsResponse: """Lists all chats.""" logger.info("Listing all chats.") ...
why do we base64 encode / decode the ids?
from sse_starlette.sse import EventSourceResponse router = fastapi.APIRouter( prefix="/chats", tags=["chats"], ) @router.get("") async def list_chats( include_hidden: bool = False, ucr: UserChatRepository = Depends(deps.create_user_chat_repository), limit: int | None = Query(10, gt=0, le=100), ...
@@ -21,12 +22,47 @@ async def list_chats( include_hidden: bool = False, ucr: UserChatRepository = Depends(deps.create_user_chat_repository), + limit: int | None = Query(10, gt=0, le=100), + after: str | None = None, + before: str | None = None, ) -> chat_schema.ListChatsResponse: """Lists all ...
inference/server/oasst_inference_server/routes/chats.py
26
Python
0.071
question
41
51
51
false
support pagination for chat list
2,773
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
notmd
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/routes/chats.py PR Title: support pagination for chat list BEFORE CODE: router = fastapi.APIRouter( prefix="/chats", tags=["chats"], ) @router.get("") async def list_chats( include_hidden: bool = False, ...
why do we base64 encode / decode the ids?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
from enum import Enum, unique class Mode(Enum): sft = "sft" rm = "rm" rl = "rl" @unique class Language(str, Enum): AB = "ab" # Abkhazian AA = "aa" # Afar AF = "af" # Afrikaans AK = "ak" # Akan SQ = "sq" # Albanian AM = "am" # Amharic AR = "ar" # Arabic AN = "an" #...
Are these all BCP 47 lang-codes? Should document which standard is used, the human-demonstration collection backend uses BCP 47. We might also think about using a lib like for example https://pypi.org/project/langcodes/ ?
from enum import Enum class Mode(Enum): sft = "sft" rm = "rm" rl = "rl"
@@ -0,0 +1,195 @@ +from enum import Enum, unique + + +class Mode(Enum): + sft = "sft" + rm = "rm" + rl = "rl" + + +@unique +class Language(str, Enum): + AB = "ab" # Abkhazian + AA = "aa" # Afar + AF = "af" # Afrikaans + AK = "ak" # Akan + SQ = "sq" # Albanian + AM = "am" # Amharic
model/model_training/custom_datasets/entities.py
17
Python
0.5
question
222
42
8
false
update entities
2,809
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
CloseChoice
Review this pull request change. Language: Python File: model/model_training/custom_datasets/entities.py PR Title: update entities BEFORE CODE: from enum import Enum, unique class Mode(Enum): sft = "sft" rm = "rm" rl = "rl" @unique class Language(str, Enum): AB = "ab" # Abkhazian AA = "aa" ...
Are these all BCP 47 lang-codes? Should document which standard is used, the human-demonstration collection backend uses BCP 47. We might also think about using a lib like for example https://pypi.org/project/langcodes/ ?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
ActionRowBuilder, ButtonStyle, ButtonBuilder, } from "discord.js"; import { createInferenceClient } from "../modules/inference/client.js"; import redis from "../modules/redis.js"; export default { disablePing: null, data: new SlashCommandBuilder() .setName("chat") .setDescription("Chat with an Open A...
It would be best if the list of available models in the future would be requested at the inference-server (/models endpoint). It will be constantly changing .. you were probably irritated that so many are displayed in the staging environment .. but that's really only a "problem" in staging.
ActionRowBuilder, ButtonStyle, ButtonBuilder, } from "discord.js"; import redis from "../modules/redis.js"; import chatFN from "../modules/chat.js"; export default { disablePing: null, data: new SlashCommandBuilder() .setName("chat") .setDescription("Chat with an Open Assistant AI.") .addStringOp...
@@ -23,10 +23,16 @@ export default { .setName("model") .setDescription("The model you want to use for the AI.") .setRequired(false) - .addChoices({ - name: "OA_SFT_Llama_30B", - value: "OA_SFT_Llama_30B", - }) + .addChoices( + { + nam...
discord-bots/oa-bot-js/src/commands/chat.ts
26
TypeScript
0.429
suggestion
291
51
51
false
Discord bot: Pythia model
2,831
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
mrloldev
Review this pull request change. Language: TypeScript File: discord-bots/oa-bot-js/src/commands/chat.ts PR Title: Discord bot: Pythia model BEFORE CODE: ActionRowBuilder, ButtonStyle, ButtonBuilder, } from "discord.js"; import { createInferenceClient } from "../modules/inference/client.js"; import redis from ...
It would be best if the list of available models in the future would be requested at the inference-server (/models endpoint). It will be constantly changing .. you were probably irritated that so many are displayed in the staging environment .. but that's really only a "problem" in staging.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
setMessages((messages) => [...messages, dummyMessage]); prompter_message = await post(API_ROUTES.CREATE_PROMPTER_MESSAGE, { arg: prompter_arg }); // filter out the dummy message and push the real one setMessages((messages) => [...messages.filter((m) => m.id !== "__dummy__"), prompter_mes...
This is a magic number, I tested on different screen widths and found this is the most optimal one lol
setMessages((messages) => [...messages, dummyMessage]); prompter_message = await post(API_ROUTES.CREATE_PROMPTER_MESSAGE, { arg: prompter_arg }); // filter out the dummy message and push the real one setMessages((messages) => [...messages.filter((m) => m.id !== "__dummy__"), prompter_mes...
@@ -200,6 +200,22 @@ export const ChatConversation = memo(function ChatConversation({ chatId, getConf [createAndFetchAssistantMessage, isSending, setIsSending] ); + const messagesEndRef = useRef<HTMLDivElement>(null); + const chatContainerRef = useRef<HTMLDivElement>(null); + + useEffect(() => { + if (!...
website/src/components/Chat/ChatConversation.tsx
26
TypeScript
0.357
suggestion
102
51
51
false
Implement auto scroll when stream message
2,839
LAION-AI/Open-Assistant
29,137
Python
notmd
notmd
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatConversation.tsx PR Title: Implement auto scroll when stream message BEFORE CODE: setMessages((messages) => [...messages, dummyMessage]); prompter_message = await post(API_ROUTES.CREATE_PROMPTER_MESSAGE, { ar...
This is a magic number, I tested on different screen widths and found this is the most optimal one lol
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { useEffect } from "react"; import { useFormContext } from "react-hook-form"; import { ChatConfigFormData } from "src/types/Chat"; import { setConfigCache } from "src/utils/chat"; export const ChatConfigSaver = () => { const { watch } = useFormContext<ChatConfigFormData>(); const config = watch(); useEffe...
when we change presets, we use the function `reset`, which sets the `isDirty` to false, so we are not saving.
import { useEffect } from "react"; import { useFormContext } from "react-hook-form"; import { ChatConfigFormData } from "src/types/Chat"; import { setConfigCache } from "src/utils/chat"; export const ChatConfigSaver = () => { const { watch, formState } = useFormContext<ChatConfigFormData>(); const config = watch()...
@@ -4,14 +4,11 @@ import { ChatConfigFormData } from "src/types/Chat"; import { setConfigCache } from "src/utils/chat"; export const ChatConfigSaver = () => { - const { watch, formState } = useFormContext<ChatConfigFormData>(); + const { watch } = useFormContext<ChatConfigFormData>(); const config = watch(); ...
website/src/components/Chat/ChatConfigSaver.tsx
11
TypeScript
0.571
suggestion
109
15
17
false
Fix saving model between chats
2,843
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
AbdBarho
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatConfigSaver.tsx PR Title: Fix saving model between chats BEFORE CODE: import { useEffect } from "react"; import { useFormContext } from "react-hook-form"; import { ChatConfigFormData } from "src/types/Chat"; import { setConf...
when we change presets, we use the function `reset`, which sets the `isDirty` to false, so we are not saving.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
return pydantic.parse_obj_as(Configuration, json_data) def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--device", default="cuda", type=str, help="device to use") parser.add_argument("--device-index", default=0, type=int, help="device index") parser.add_argument("--model-...
Can we call this `--int8`? Could be confusing as-is, as `--half` is also quantisation
return pydantic.parse_obj_as(Configuration, json_data) def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--device", default="cuda", type=str, help="device to use") parser.add_argument("--device-index", default=0, type=int, help="device index") parser.add_argument("--model-...
@@ -226,6 +226,7 @@ def parse_args(): parser.add_argument("--num-samples", type=int, default=2, help="number of sampling runs per configuration") parser.add_argument("--config", type=str, default="config/default.json", help="configuration file path") parser.add_argument("--half", action="store_true", def...
model/model_eval/manual/sampling_report.py
26
Python
0.429
question
85
51
51
false
Add quantization/8bit model loading support for sampling_report.py
2,857
LAION-AI/Open-Assistant
29,137
Python
olliestanley
toiletpapercode
Review this pull request change. Language: Python File: model/model_eval/manual/sampling_report.py PR Title: Add quantization/8bit model loading support for sampling_report.py BEFORE CODE: return pydantic.parse_obj_as(Configuration, json_data) def parse_args(): parser = argparse.ArgumentParser() pars...
Can we call this `--int8`? Could be confusing as-is, as `--half` is also quantisation
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { withoutRole } from "src/lib/auth"; import { isChatEnable } from "src/lib/isChatEnable"; import { createInferenceClient } from "src/lib/oasst_inference_client"; const handler = withoutRole("banned", async (req, res, token) => { if (!isChatEnable()) { return res.status(404).end(); } const client = cre...
Can you remove this option and hard code it to this file?
import { withoutRole } from "src/lib/auth"; import { isChatEnable } from "src/lib/isChatEnable"; import { createInferenceClient } from "src/lib/oasst_inference_client"; import { GetChatsParams } from "src/types/Chat"; export const PAGE_SIZE = 20; const handler = withoutRole("banned", async (req, res, token) => { if...
@@ -13,7 +13,17 @@ const handler = withoutRole("banned", async (req, res, token) => { if (req.query.chat_id) { data = await client.get_chat(req.query.chat_id as string); } else { - data = await client.get_my_chats(); + const params = {}; + if (req.query.limit) {
website/src/pages/api/chat/index.ts
17
TypeScript
0.286
refactor
57
42
42
false
feat(website): support pagination for chat list
2,860
LAION-AI/Open-Assistant
29,137
Python
notmd
mtosity
Review this pull request change. Language: TypeScript File: website/src/pages/api/chat/index.ts PR Title: feat(website): support pagination for chat list BEFORE CODE: import { withoutRole } from "src/lib/auth"; import { isChatEnable } from "src/lib/isChatEnable"; import { createInferenceClient } from "src/lib/oasst...
Can you remove this option and hard code it to this file?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { withoutRole } from "src/lib/auth"; import { isChatEnable } from "src/lib/isChatEnable"; import { createInferenceClient } from "src/lib/oasst_inference_client"; export const PAGE_SIZE = 20; const handler = withoutRole("banned", async (req, res, token) => { if (!isChatEnable()) { return res.status(404).e...
please add type `params: GetChatParams` just to be sure. Otherwise looks good!
import { withoutRole } from "src/lib/auth"; import { isChatEnable } from "src/lib/isChatEnable"; import { createInferenceClient } from "src/lib/oasst_inference_client"; import { GetChatsParams } from "src/types/Chat"; export const PAGE_SIZE = 20; const handler = withoutRole("banned", async (req, res, token) => { if...
@@ -13,7 +15,16 @@ const handler = withoutRole("banned", async (req, res, token) => { if (req.query.chat_id) { data = await client.get_chat(req.query.chat_id as string); } else { - data = await client.get_my_chats(); + const params = {
website/src/pages/api/chat/index.ts
18
TypeScript
0.5
suggestion
81
43
43
false
feat(website): support pagination for chat list
2,860
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
mtosity
Review this pull request change. Language: TypeScript File: website/src/pages/api/chat/index.ts PR Title: feat(website): support pagination for chat list BEFORE CODE: import { withoutRole } from "src/lib/auth"; import { isChatEnable } from "src/lib/isChatEnable"; import { createInferenceClient } from "src/lib/oasst...
please add type `params: GetChatParams` just to be sure. Otherwise looks good!
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
</> ); }; type WithSpanCell<T> = Cell<T, unknown> & { span?: number }; const DataTableRow = <T,>({ row }: { row: Row<T> }) => { const cells: WithSpanCell<T>[] = row.getVisibleCells(); const renderCells: WithSpanCell<T>[] = []; for (let i = 0; i < cells.length; i++) { const cell = cells[i]; const ...
We dont want to add this bahavior on the DataTable component
</> ); }; type WithSpanCell<T> = Cell<T, unknown> & { span?: number }; const DataTableRow = <T,>({ row }: { row: Row<T> }) => { const cells: WithSpanCell<T>[] = row.getVisibleCells(); const renderCells: WithSpanCell<T>[] = []; for (let i = 0; i < cells.length; i++) { const cell = cells[i]; const ...
@@ -199,7 +199,7 @@ const DataTableRow = <T,>({ row }: { row: Row<T> }) => { {renderCells.map((cell) => { const props = cell.column.columnDef.meta?.cellProps?.(cell); return ( - <Td key={cell.id} {...props} colSpan={cell.span}> + <Td key={cell.id} {...props} colSpan={cell.span...
website/src/components/DataTable/DataTable.tsx
26
TypeScript
0.214
suggestion
60
51
51
false
Fix display name spill-over (#2851)
2,863
LAION-AI/Open-Assistant
29,137
Python
notmd
scorbett123
Review this pull request change. Language: TypeScript File: website/src/components/DataTable/DataTable.tsx PR Title: Fix display name spill-over (#2851) BEFORE CODE: </> ); }; type WithSpanCell<T> = Cell<T, unknown> & { span?: number }; const DataTableRow = <T,>({ row }: { row: Row<T> }) => { const cells:...
We dont want to add this bahavior on the DataTable component
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
class JokeExplaination(Dataset): name = "joke" url = "https://gist.github.com/theblackcat102/42b697e24a13fdb499e20edfbf618361/raw/1834dca207898c15f93b809d1195f6f6e47c9e1e/joke_explained.jsonl" def __init__(self, cache_dir) -> None: super().__init__() os.makedirs(cache_dir, exist_ok=True) ...
you rely here on the order of the keywords. Could we make this explicit by using ```suggestion self.pairs.append(DatasetEntry(questions=[joke], answers=[explanation])) ```
class JokeExplaination(Dataset): name = "joke" url = "https://gist.github.com/theblackcat102/42b697e24a13fdb499e20edfbf618361/raw/1834dca207898c15f93b809d1195f6f6e47c9e1e/joke_explained.jsonl" def __init__(self, cache_dir) -> None: super().__init__() os.makedirs(cache_dir, exist_ok=True) ...
@@ -343,16 +343,16 @@ def __init__(self, cache_dir) -> None: # DO NOT change this # its the data that had syntax error explanation = data["explaination"] - self.pairs.append((joke, explanation)) + self.pairs.append(DatasetEntry([joke], [ex...
model/model_training/custom_datasets/qa_datasets.py
26
Python
0.786
suggestion
190
51
51
false
Joke explanation generalization
2,899
LAION-AI/Open-Assistant
29,137
Python
CloseChoice
sampatkalyan
Review this pull request change. Language: Python File: model/model_training/custom_datasets/qa_datasets.py PR Title: Joke explanation generalization BEFORE CODE: class JokeExplaination(Dataset): name = "joke" url = "https://gist.github.com/theblackcat102/42b697e24a13fdb499e20edfbf618361/raw/1834dca207898c...
you rely here on the order of the keywords. Could we make this explicit by using ```suggestion self.pairs.append(DatasetEntry(questions=[joke], answers=[explanation])) ```
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
url = "https://gist.github.com/theblackcat102/42b697e24a13fdb499e20edfbf618361/raw/1834dca207898c15f93b809d1195f6f6e47c9e1e/joke_explained.jsonl" def __init__(self, cache_dir) -> None: super().__init__() os.makedirs(cache_dir, exist_ok=True) joke_explain_filename = os.path.join(cache_di...
You mentioned already that question and answer are not use, so please remove them and also this `if` statement.
url = "https://gist.github.com/theblackcat102/42b697e24a13fdb499e20edfbf618361/raw/1834dca207898c15f93b809d1195f6f6e47c9e1e/joke_explained.jsonl" def __init__(self, cache_dir) -> None: super().__init__() os.makedirs(cache_dir, exist_ok=True) joke_explain_filename = os.path.join(cache_di...
@@ -343,16 +343,16 @@ def __init__(self, cache_dir) -> None: # DO NOT change this # its the data that had syntax error explanation = data["explaination"] - self.pairs.append((joke, explanation)) + self.pairs.append(DatasetEntry([joke], [ex...
model/model_training/custom_datasets/qa_datasets.py
26
Python
0.571
suggestion
111
51
51
false
Joke explanation generalization
2,899
LAION-AI/Open-Assistant
29,137
Python
CloseChoice
sampatkalyan
Review this pull request change. Language: Python File: model/model_training/custom_datasets/qa_datasets.py PR Title: Joke explanation generalization BEFORE CODE: url = "https://gist.github.com/theblackcat102/42b697e24a13fdb499e20edfbf618361/raw/1834dca207898c15f93b809d1195f6f6e47c9e1e/joke_explained.jsonl" ...
You mentioned already that question and answer are not use, so please remove them and also this `if` statement.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { Box } from "@chakra-ui/react"; export const ChatWarning = () => { return ( <Box fontSize="sm" textAlign="center" mb="2" className="max-w-5xl mx-auto"> This Assistant is a demonstration version that does not have internet access. It may generate incorrect or misleading information. It is not ...
can we put this back into the locale? we want it to be translated.
import { Box } from "@chakra-ui/react"; import { useTranslation } from "next-i18next"; export const ChatWarning = () => { const { t } = useTranslation("chat"); return ( <Box fontSize="sm" textAlign="center" mb="2" className="max-w-5xl mx-auto"> {t("warning")} </Box> ); };
@@ -1,27 +1,10 @@ -import { Flex } from "@chakra-ui/react"; -import { Fragment } from "react"; -import { TeamMember } from "src/components/TeamMember"; - -import data from "../../data/warning.json"; - -const warn = ["warning"] as const; - -const rootProps = { - bg: "transparent", - borderRadius: 0, -}; +import { Box ...
website/src/components/Chat/ChatWarning.tsx
7
TypeScript
0.214
question
66
11
12
false
update chat warning design
2,924
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
notmd
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatWarning.tsx PR Title: update chat warning design BEFORE CODE: import { Box } from "@chakra-ui/react"; export const ChatWarning = () => { return ( <Box fontSize="sm" textAlign="center" mb="2" className="max-w-5xl mx-au...
can we put this back into the locale? we want it to be translated.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
def __getitem__(self, index): return self.data[index] def load_oasst_export( input_file_path: str | Path, hf_dataset_name: str, val_split: float = 0.2, lang: str = "en", top_k: Optional[int] = None, manual_seed: int = 287631038922, data_path: str | Path = None, use_hf_datas...
The format between trees and messages in the HF dataset differs greatly .. some conversion is required to restore the OA format.
def __getitem__(self, index): return self.data[index] def load_oasst_export( input_file_path: Optional[str | Path] = None, hf_dataset_name: Optional[str] = "OpenAssistant/oasst1", val_split: float = 0.2, lang: str = "en", top_k: Optional[int] = None, manual_seed: int = 28763103892...
@@ -35,6 +38,10 @@ def load_oasst_export( generator = Generator() generator.manual_seed(manual_seed) + if use_hf_dataset and hf_dataset_name: + hf_dataset = load_dataset(hf_dataset_name) + return hf_dataset["train"], hf_dataset["validation"]
model/model_training/custom_datasets/oasst_dataset.py
26
Python
0.357
style
128
51
51
false
Add data loader for HF oasst1
2,951
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
grgau
Review this pull request change. Language: Python File: model/model_training/custom_datasets/oasst_dataset.py PR Title: Add data loader for HF oasst1 BEFORE CODE: def __getitem__(self, index): return self.data[index] def load_oasst_export( input_file_path: str | Path, hf_dataset_name: str, ...
The format between trees and messages in the HF dataset differs greatly .. some conversion is required to restore the OA format.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
from __future__ import annotations from datetime import datetime from typing import Literal, Optional from pydantic import BaseModel, conint class LabelAvgValue(BaseModel): value: float | None count: int LabelValues = dict class ExportMessageEvent(BaseModel): type: str user_id: str | None clas...
What is the reason for this change (and the similar one for `emojis` below)?
from __future__ import annotations from datetime import datetime from typing import Literal, Optional from pydantic import BaseModel, conint class LabelAvgValue(BaseModel): value: float | None count: int LabelValues = dict[str, LabelAvgValue] class ExportMessageEvent(BaseModel): type: str user_i...
@@ -11,7 +11,7 @@ class LabelAvgValue(BaseModel): count: int -LabelValues = dict[str, LabelAvgValue]
oasst-data/oasst_data/schemas.py
14
Python
0.429
question
76
39
39
false
Add data loader for HF oasst1
2,951
LAION-AI/Open-Assistant
29,137
Python
olliestanley
grgau
Review this pull request change. Language: Python File: oasst-data/oasst_data/schemas.py PR Title: Add data loader for HF oasst1 BEFORE CODE: from __future__ import annotations from datetime import datetime from typing import Literal, Optional from pydantic import BaseModel, conint class LabelAvgValue(BaseModel...
What is the reason for this change (and the similar one for `emojis` below)?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
onError: () => { toast({ title: "Failed to load chat", status: "error", }); }, }); const createAndFetchAssistantMessage = useCallback( async ({ parentId, chatId }: { parentId: string; chatId: string }) => { const { model_config_name, ...sampling_parameters } = getConfi...
This always is `OasstError` since we already transformed the error, the check to make TS happy
}, onError: () => { toast({ title: "Failed to load chat", status: "error", }); }, }); const createAndFetchAssistantMessage = useCallback( async ({ parentId, chatId }: { parentId: string; chatId: string }) => { const { model_config_name, ...sampling_parameters } = g...
@@ -58,9 +59,21 @@ export const ChatConversation = memo(function ChatConversation({ chatId, getConf sampling_parameters, }; - const assistant_message: InferenceMessage = await post(API_ROUTES.CREATE_ASSISTANT_MESSAGE, { - arg: assistant_arg, - }); + let assistant_message: Inferen...
website/src/components/Chat/ChatConversation.tsx
26
TypeScript
0.5
suggestion
94
51
51
false
Handle chat error
2,959
LAION-AI/Open-Assistant
29,137
Python
notmd
notmd
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatConversation.tsx PR Title: Handle chat error BEFORE CODE: onError: () => { toast({ title: "Failed to load chat", status: "error", }); }, }); const createAndFetchAssistantMessage = use...
This always is `OasstError` since we already transformed the error, the check to make TS happy
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
Stack, Textarea, useDisclosure, } from "@chakra-ui/react"; import { Cog, Edit, Plus } from "lucide-react"; import { AttachmentIcon, WarningIcon, CheckCircleIcon, CloseIcon } from "@chakra-ui/icons"; import { ChangeEvent, useCallback, useMemo, useEffect, useState, useRef } from "react"; import { useTranslation } f...
Since you alreay has a fall back `|| []`, I don't think we need `?` and `?? - 1` here anymore ```suggestion return plugins.findIndex((plugin) => plugin.enabled); ```
Stack, Textarea, useDisclosure, } from "@chakra-ui/react"; import { Cog, Edit, Plus } from "lucide-react"; import { AttachmentIcon, WarningIcon, CheckCircleIcon, CloseIcon } from "@chakra-ui/icons"; import { ChangeEvent, useCallback, useMemo, useEffect, useState, useRef } from "react"; import { useTranslation } f...
@@ -56,7 +49,7 @@ export const PluginsChooser = ({ plugins }: { plugins: PluginEntry[] }) => { const containerRef = useRef<HTMLDivElement | null>(null); const activePluginIndex = useMemo(() => { - return plugins.findIndex((plugin) => plugin.enabled); + return plugins?.findIndex((plugin) => plugin.enabled)...
website/src/components/Chat/PluginsChooser.tsx
26
TypeScript
0.714
suggestion
172
51
51
false
Fixed PluginChooser button width problem
3,014
LAION-AI/Open-Assistant
29,137
Python
notmd
draganjovanovich
Review this pull request change. Language: TypeScript File: website/src/components/Chat/PluginsChooser.tsx PR Title: Fixed PluginChooser button width problem BEFORE CODE: Stack, Textarea, useDisclosure, } from "@chakra-ui/react"; import { Cog, Edit, Plus } from "lucide-react"; import { AttachmentIcon, Warning...
Since you alreay has a fall back `|| []`, I don't think we need `?` and `?? - 1` here anymore ```suggestion return plugins.findIndex((plugin) => plugin.enabled); ```
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
const plugin: PluginEntry = await post(API_ROUTES.GET_PLUGIN_CONFIG, { arg: { plugin: newPlugins[selectedForEditPluginIndex!] }, }); // disable all existing plugins and enable new one newPlugins.forEach((plugin) => (plugin.enabled = false)); newPlugins[selectedForEditPluginIndex!]....
```suggestion {activePluginIndex > -1 && plugins[activePluginIndex]?.enabled ? ( ```
const plugin: PluginEntry = await post(API_ROUTES.GET_PLUGIN_CONFIG, { arg: { plugin: newPlugins[selectedForEditPluginIndex!] }, }); // disable all existing plugins and enable new one newPlugins.forEach((plugin) => (plugin.enabled = false)); newPlugins[selectedForEditPluginIndex!]....
@@ -114,30 +107,30 @@ export const PluginsChooser = ({ plugins }: { plugins: PluginEntry[] }) => { }, [setValue, plugins, handlePluginEdit]); return ( - <FormControl mb="40px" ref={containerRef}> - <Box position="fixed" zIndex="1"> - <Menu placement="auto"> - <MenuButton as={Button} pr="...
website/src/components/Chat/PluginsChooser.tsx
26
TypeScript
0.571
suggestion
96
51
51
false
Fixed PluginChooser button width problem
3,014
LAION-AI/Open-Assistant
29,137
Python
notmd
draganjovanovich
Review this pull request change. Language: TypeScript File: website/src/components/Chat/PluginsChooser.tsx PR Title: Fixed PluginChooser button width problem BEFORE CODE: const plugin: PluginEntry = await post(API_ROUTES.GET_PLUGIN_CONFIG, { arg: { plugin: newPlugins[selectedForEditPluginIndex!] }, ...
```suggestion {activePluginIndex > -1 && plugins[activePluginIndex]?.enabled ? ( ```
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import json import re import threading import requests import transformers from chat_chain_prompts import INSTRUCTIONS, OBSERVATION_SEQ, TOOLS_PREFIX, V2_ASST_PREFIX, V2_PROMPTER_PREFIX from hf_langchain_inference import HFInference from langchain.agents import Tool from langchain.memory import ConversationBufferMemor...
Interesting! Why wasn't this detected during use and importing of the module? Does the current design fail quietly?
import json import re import requests import transformers from chat_chain_prompts import INSTRUCTIONS, OBSERVATION_SEQ, TOOLS_PREFIX, V2_ASST_PREFIX, V2_PROMPTER_PREFIX from hf_langchain_inference import HFInference from langchain.agents import Tool from langchain.memory import ConversationBufferMemory from langchain....
@@ -11,7 +11,7 @@ from langchain.prompts import PromptTemplate from loguru import logger from oasst_shared.schemas import inference -from opeanapi_parser import prepare_plugin_for_llm +from openapi_parser import prepare_plugin_for_llm
inference/worker/chat_chain_utils.py
13
Python
0.429
bug
115
38
38
false
Fix plugins
3,017
LAION-AI/Open-Assistant
29,137
Python
pevogam
olliestanley
Review this pull request change. Language: Python File: inference/worker/chat_chain_utils.py PR Title: Fix plugins BEFORE CODE: import json import re import threading import requests import transformers from chat_chain_prompts import INSTRUCTIONS, OBSERVATION_SEQ, TOOLS_PREFIX, V2_ASST_PREFIX, V2_PROMPTER_PREFIX f...
Interesting! Why wasn't this detected during use and importing of the module? Does the current design fail quietly?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
<CreateChatButton py="5" leftIcon={<Plus size="16px"></Plus>} variant="outline" justifyContent="start" colorScheme="blue" borderRadius="lg" mx="3" mb="2" onUpdated={handleCreateChat} > {t("create_chat")} </CreateChatButton...
We still need to redirect user to another page after deleting, maybe latest chat or /chat page
<CreateChatButton py="5" leftIcon={<Plus size="16px"></Plus>} variant="outline" justifyContent="start" colorScheme="blue" borderRadius="lg" mx="3" mb="2" onUpdated={handleCreateChat} > {t("create_chat")} </CreateChatButton...
@@ -98,7 +98,13 @@ export const ChatListBase = memo(function ChatListBase({ }} > {chats.map((chat) => ( - <ChatListItem key={chat.id} chat={chat} onUpdateTitle={handleUpdateTitle} onHide={handleHide} /> + <ChatListItem + key={chat.id} + chat={chat} + ...
website/src/components/Chat/ChatListBase.tsx
26
TypeScript
0.286
suggestion
94
29
35
false
add delete function
3,019
LAION-AI/Open-Assistant
29,137
Python
notmd
ruoniw
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatListBase.tsx PR Title: add delete function BEFORE CODE: <CreateChatButton py="5" leftIcon={<Plus size="16px"></Plus>} variant="outline" justifyContent="start" colorScheme="blue" ...
We still need to redirect user to another page after deleting, maybe latest chat or /chat page
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
yield token else: break def finish(self, reason: Literal["length", "eos_token", "stop_sequence"]) -> Iterable[interface.Token]: if reason == "stop_sequence": end_sequence = "" end_tokens = [] while self.tokens: ...
I think this function name is slightly misleading
yield token else: break def finish(self, reason: Literal["length", "eos_token", "stop_sequence"]) -> Iterable[interface.Token]: if reason == "stop_sequence": end_sequence = "" end_tokens = [] while self.tokens: ...
@@ -64,6 +64,19 @@ def finish(self, reason: Literal["length", "eos_token", "stop_sequence"]) -> Ite yield from self.tokens +def add_prefix_to_prompt(prompt: str):
inference/worker/utils.py
26
Python
0.071
suggestion
49
51
51
false
Cleaned up backend plugin code: Part 1
3,056
LAION-AI/Open-Assistant
29,137
Python
olliestanley
SerenityCodes
Review this pull request change. Language: Python File: inference/worker/utils.py PR Title: Cleaned up backend plugin code: Part 1 BEFORE CODE: yield token else: break def finish(self, reason: Literal["length", "eos_token", "stop_sequence"]) -> Iterable[interface.Tok...
I think this function name is slightly misleading
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
def get_max_input_length(worker_config: inference.WorkerConfig, plugin_used: bool): max_input_length = worker_config.model_config.max_input_length if plugin_used: max_input_length = max_input_length - 1 return max_input_length def truncate_prompt( tokenizer: transformers.PreTrainedTokenizer, ...
As pointed out by Yannic in #3061, this length will turn out to be calculated wrong if the prompter prefix is added above. We should adjust this
def truncate_prompt( tokenizer: transformers.PreTrainedTokenizer, worker_config: inference.WorkerConfig, parameters: interface.GenerateStreamParameters, prompt: str, plugin_used: bool, ): with shared_tokenizer_lock: ids = tokenizer.encode(prompt) max_input_length = get_max_input_le...
@@ -74,28 +87,22 @@ def truncate_prompt( with shared_tokenizer_lock: ids = tokenizer.encode(prompt) - max_input_length = worker_config.model_config.max_input_length - - # make room for prompter prefix - if plugin_used: - max_input_length = max_input_length - 1 + max_input_length = get...
inference/worker/utils.py
26
Python
0.429
bug
144
51
51
false
Cleaned up backend plugin code: Part 1
3,056
LAION-AI/Open-Assistant
29,137
Python
olliestanley
SerenityCodes
Review this pull request change. Language: Python File: inference/worker/utils.py PR Title: Cleaned up backend plugin code: Part 1 BEFORE CODE: def get_max_input_length(worker_config: inference.WorkerConfig, plugin_used: bool): max_input_length = worker_config.model_config.max_input_length if plugin_used: ...
As pointed out by Yannic in #3061, this length will turn out to be calculated wrong if the prompter prefix is added above. We should adjust this
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
ids = ids[-(max_input_length - 1) :] with shared_tokenizer_lock: prompt = tokenizer.decode(ids) prompt = add_prefix_to_prompt(prompt) input_length = len(ids) spare = max_total_tokens - input_length - 1 if not parameters.max_new_tokens: parameters.max_new_toke...
I think this one should remain `warning`, it's relevant outside of debugging.
ids = tokenizer.encode(V2_PROMPTER_PREFIX) + ids max_total_tokens = worker_config.model_config.max_total_length input_length = len(ids) spare = max_total_tokens - input_length - 1 if not parameters.max_new_tokens: parameters.max_new_tokens = spare elif parameters.max_new_to...
@@ -110,7 +117,7 @@ def wait_for_inference_server(http: "HttpClient", timeout: int = 600): if time.time() > time_limit: raise sleep_duration = random.uniform(0, 10) - logger.warning(f"Inference server not ready. Retrying in {sleep_duration:.2f} seconds") + ...
inference/worker/utils.py
26
Python
0.571
bug
77
51
51
false
Cleaned up backend plugin code: Part 1
3,056
LAION-AI/Open-Assistant
29,137
Python
olliestanley
SerenityCodes
Review this pull request change. Language: Python File: inference/worker/utils.py PR Title: Cleaned up backend plugin code: Part 1 BEFORE CODE: ids = ids[-(max_input_length - 1) :] with shared_tokenizer_lock: prompt = tokenizer.decode(ids) prompt = add_prefix_to_prompt(prompt...
I think this one should remain `warning`, it's relevant outside of debugging.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { Badge } from "@chakra-ui/react"; // kept brief so that it doesnt distract/interfere with user experience export const EncourageMessage = () => { return ( <Badge ml="1" fontFamily="Geneva" fontWeight="normal" fontSize="0.4em" background="gray.300" color="black"> Thoughts? Let us know! </Badge> ...
can you move this to the localization?
import { Badge } from "@chakra-ui/react"; import { useTranslation } from "next-i18next"; // kept brief so that it doesnt distract/interfere with user experience export const EncourageMessage = () => { const { t } = useTranslation("chat"); return ( <Badge fontWeight="normal" background="gray.300" color="black"> ...
@@ -0,0 +1,10 @@ +import { Badge } from "@chakra-ui/react"; + +// kept brief so that it doesnt distract/interfere with user experience +export const EncourageMessage = () => { + return ( + <Badge ml="1" fontFamily="Geneva" fontWeight="normal" fontSize="0.4em" background="gray.300" color="black"> + Thoughts? Le...
website/src/components/Chat/EncourageMessage.tsx
7
TypeScript
0.143
refactor
38
11
12
false
Created feedback encouragement message
3,057
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
amitag2
Review this pull request change. Language: TypeScript File: website/src/components/Chat/EncourageMessage.tsx PR Title: Created feedback encouragement message BEFORE CODE: import { Badge } from "@chakra-ui/react"; // kept brief so that it doesnt distract/interfere with user experience export const EncourageMessage ...
can you move this to the localization?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.