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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
}
if (!passed_explicit && depwarn)
*depwarn |= (*bpart)->kind & PARTITION_FLAG_DEPWARN;
if (kind != PARTITION_KIND_IMPLICIT_GLOBAL)
passed_explicit = 1;
*bnd = (jl_binding_t*)(*bpart)->restriction;
*bpart = jl_get_binding_partition(*bnd, world);
}
}
... | No issues found. | }
if (!passed_explicit && depwarn)
*depwarn |= (*bpart)->kind & PARTITION_FLAG_DEPWARN;
if (kind != PARTITION_KIND_IMPLICIT_GLOBAL)
passed_explicit = 1;
*bnd = (jl_binding_t*)(*bpart)->restriction;
*bpart = jl_get_binding_partition(*bnd, world);
}
}
... | @@ -2021,10 +2021,14 @@ struct _jl_image_fptrs_t;
JL_DLLEXPORT void jl_write_coverage_data(const char*);
void jl_write_malloc_log(void);
-#if jl_has_builtin(__builtin_unreachable) || defined(_COMPILER_GCC_) || defined(_COMPILER_INTEL_)
-# define jl_unreachable() __builtin_unreachable()
+#ifdef JL_NDEBUG
+# if jl_h... | src/julia_internal.h | 0 | C/C++ | 1 | none | 16 | 51 | 51 | true | Make jl_assume, jl_assume_aligned, jl_unreachable asserts in debug | 61,015 | JuliaLang/julia | 35,573 | Julia | xal-0 | Review this pull request change.
Language: C/C++
File: src/julia_internal.h
PR Title: Make jl_assume, jl_assume_aligned, jl_unreachable asserts in debug
BEFORE CODE: }
if (!passed_explicit && depwarn)
*depwarn |= (*bpart)->kind & PARTITION_FLAG_DEPWARN;
if (kind != PARTITION_KIND... | No issues found. | 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. | |
end
#---------------------
LoweringError:
macro mmm[](ex)
# └───┘ ── invalid macro name
end
########################################
# Error: Macros not allowed in local scope
let
macro foo(ex)
end
end
#---------------------
LoweringError:
let
# ┌────────────
macro foo(ex)
end
#─────┘ ── macro is... | No issues found. | end
#---------------------
LoweringError:
macro mmm[](ex)
# └───┘ ── invalid macro name
end
########################################
# Error: Macros not allowed in local scope
let
macro foo(ex)
end
end
#---------------------
LoweringError:
let
# ┌────────────
macro foo(ex)
end
#─────┘ ── macro is... | @@ -208,3 +208,54 @@ end
10 latestworld
11 TestMod.foo
12 (return %₁₁)
+
+########################################
+# @nospecialize (single arg in body)
+function foo(a, b)
+ @nospecialize a
+ a + b
+end
+#---------------------
+1 (method TestMod.foo)
+2 latestworld
+3 TestMod.foo
+4 (call core.Type... | JuliaLowering/test/macros_ir.jl | 0 | Julia | 1 | none | 16 | 51 | 51 | true | [JuliaLowering] Fix `@nospecialize` multi-arg and add 0-arg | 61,021 | JuliaLang/julia | 35,573 | Julia | aviatesk | Review this pull request change.
Language: Julia
File: JuliaLowering/test/macros_ir.jl
PR Title: [JuliaLowering] Fix `@nospecialize` multi-arg and add 0-arg
BEFORE CODE: end
#---------------------
LoweringError:
macro mmm[](ex)
# └───┘ ── invalid macro name
end
########################################
# Error:... | No issues found. | 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. | |
@testset "assert_syntaxtree" begin
st = parsestmt(SyntaxTree, "function foo end")
g = st._graph
@test JuliaLowering.assert_syntaxtree(st) === nothing
bad_st = JuliaSyntax.newleaf(g, st, K"Identifier")
@test_throws "needs attribute name_val" JuliaLowering.assert_syntaxtree(bad_st)
@test_throws "... | No issues found. | @testset "assert_syntaxtree" begin
st = parsestmt(SyntaxTree, "function foo end")
g = st._graph
@test JuliaLowering.assert_syntaxtree(st) === nothing
bad_st = JuliaSyntax.newleaf(g, st, K"Identifier")
@test_throws "needs attribute name_val" JuliaLowering.assert_syntaxtree(bad_st)
@test_throws "... | @@ -0,0 +1,24 @@
+@testset "assert_syntaxtree" begin
+ st = parsestmt(SyntaxTree, "function foo end")
+ g = st._graph
+ @test JuliaLowering.assert_syntaxtree(st) === nothing
+
+ bad_st = JuliaSyntax.newleaf(g, st, K"Identifier")
+ @test_throws "needs attribute name_val" JuliaLowering.assert_syntaxtree(ba... | JuliaLowering/test/ast.jl | 0 | Julia | 1 | none | 16 | 25 | 25 | true | [JuliaLowering] Printing improvements: malformed trees, leaf kinds | 61,028 | JuliaLang/julia | 35,573 | Julia | mlechu | Review this pull request change.
Language: Julia
File: JuliaLowering/test/ast.jl
PR Title: [JuliaLowering] Printing improvements: malformed trees, leaf kinds
BEFORE CODE: @testset "assert_syntaxtree" begin
st = parsestmt(SyntaxTree, "function foo end")
g = st._graph
@test JuliaLowering.assert_syntaxtree... | No issues found. | 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_order_kwargs(; by = identity, func = isless, rev = false) = get_order(by, func, rev)
# test that this doesn't cause an internal error
get_order_kwargs()
end
# Test that tail-like functions don't block constant propagation
my_tail_const_prop(i, tail...) = tail
function foo_tail_const_prop()
Val{my_tail_const_p... | No issues found. | get_order_kwargs(; by = identity, func = isless, rev = false) = get_order(by, func, rev)
# test that this doesn't cause an internal error
get_order_kwargs()
end
# Test that tail-like functions don't block constant propagation
my_tail_const_prop(i, tail...) = tail
function foo_tail_const_prop()
Val{my_tail_const_p... | @@ -4088,6 +4088,84 @@ end
end
end
+@testset "alias-aware union splitting" begin
+ let 𝕃 = Compiler.fallback_lattice
+ argtypes = Any[typeof(+), Union{Int,Float64}, Union{Int,Float64}]
+ # without aliasing: 2 * 2 = 4
+ @test Compiler.unionsplitcost(𝕃, argtypes) == 4
+ @test leng... | Compiler/test/inference.jl | 0 | Julia | 1 | none | 16 | 51 | 51 | true | inference: Alias-aware union splitting for identical arguments | 61,041 | JuliaLang/julia | 35,573 | Julia | aviatesk | Review this pull request change.
Language: Julia
File: Compiler/test/inference.jl
PR Title: inference: Alias-aware union splitting for identical arguments
BEFORE CODE: get_order_kwargs(; by = identity, func = isless, rev = false) = get_order(by, func, rev)
# test that this doesn't cause an internal error
get_order... | No issues found. | 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. | |
end
end
end
with(sval_float=>2.0) do
nth_with(15) do
@test sval_float[] == 2.0
with(sval_float => 3.0) do
@test sval_float[] == 3.0
end
end
end
end
@testset "macro" begin
@with sval=>2 sval_float=>2.0 begin
... | No issues found. | end
end
end
with(sval_float=>2.0) do
nth_with(15) do
@test sval_float[] == 2.0
with(sval_float => 3.0) do
@test sval_float[] == 3.0
end
end
end
end
@testset "macro" begin
@with sval=>2 sval_float=>2.0 begin
... | @@ -268,3 +268,20 @@ end
@testset "issue 59483" begin
test_59483()
end
+
+# issue #53584 - ScopedValue should not allocate when accessed
+const sv_53584 = ScopedValue([0])
+@noinline function access_scoped_53584()
+ v = sv_53584[]
+ v[1] += 1
+ return nothing
+end
+function run_53584()
+ @with sv_535... | test/scopedvalues.jl | 0 | Julia | 1 | none | 16 | 51 | 51 | true | optimizer: Switch to `Some{}` in PersistentDict optimized generics | 61,053 | JuliaLang/julia | 35,573 | Julia | Keno | Review this pull request change.
Language: Julia
File: test/scopedvalues.jl
PR Title: optimizer: Switch to `Some{}` in PersistentDict optimized generics
BEFORE CODE: end
end
end
with(sval_float=>2.0) do
nth_with(15) do
@test sval_float[] == 2.0
with(sval_f... | No issues found. | 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. | |
@test count(contains(runtests * ":10"), lines) == 1 # @testset
@test count(contains(runtests * ":11"), lines) == 1 # test
fail = failures[3]; lines = split(fail.stacktrace, '\n')
@test length(lines)/2 ≤ 6
@test fail.testset == "Tests" && fail.source == test_properties2_macro_source && fail.ex == "i... | No issues found. | @test count(contains(runtests * ":10"), lines) == 1 # @testset
@test count(contains(runtests * ":11"), lines) == 1 # test
fail = failures[3]; lines = split(fail.stacktrace, '\n')
@test length(lines)/2 ≤ 6
@test fail.testset == "Tests" && fail.source == test_properties2_macro_source && fail.ex == "i... | @@ -422,7 +422,11 @@ let fails = @testset NoThrowTestSet begin
@test typeof(1) <: typeof("julia")
# 29 - Fail - assignment
@test (i = length([1, 2])) == 3
- # 30 - 33 - Fail - wrong message
+ # 30 - Fail - symbol comparison
+ @test 1 + 2 == :sym
+ # 31 - Fail - sym... | stdlib/Test/test/runtests.jl | 0 | Julia | 1 | none | 16 | 51 | 51 | true | Test: quote Symbol values in @test failure pretty printing | 61,054 | JuliaLang/julia | 35,573 | Julia | apoorvdarshan | Review this pull request change.
Language: Julia
File: stdlib/Test/test/runtests.jl
PR Title: Test: quote Symbol values in @test failure pretty printing
BEFORE CODE: @test count(contains(runtests * ":10"), lines) == 1 # @testset
@test count(contains(runtests * ":11"), lines) == 1 # test
fail = failures... | No issues found. | 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. | |
########################################
# Error: local with two type declarations, requiring scope resolution
begin
local x::Int = 1
x::Int = 1
end
#---------------------
LoweringError:
begin
local x::Int = 1
x::Int = 1
# └────────┘ ── multiple type declarations found for `x`
end
###################... | No issues found. | ########################################
# Error: local with two type declarations, requiring scope resolution
begin
local x::Int = 1
x::Int = 1
end
#---------------------
LoweringError:
begin
local x::Int = 1
x::Int = 1
# └────────┘ ── multiple type declarations found for `x`
end
###################... | @@ -193,7 +193,7 @@ global xx::T = 10
16 (return 10)
########################################
-# Error: x declared twice
+# Error: local with two type declarations
begin
local x::T = 1
local x::S = 1
@@ -206,6 +206,47 @@ begin
# └───────┘ ── multiple type declarations found for `x`
end
+#####... | JuliaLowering/test/decls_ir.jl | 0 | Julia | 1 | none | 16 | 51 | 51 | true | [JuliaLowering] Several small bugfixes found in stdlib testing | 61,070 | JuliaLang/julia | 35,573 | Julia | mlechu | Review this pull request change.
Language: Julia
File: JuliaLowering/test/decls_ir.jl
PR Title: [JuliaLowering] Several small bugfixes found in stdlib testing
BEFORE CODE: ########################################
# Error: local with two type declarations, requiring scope resolution
begin
local x::Int = 1
x:... | No issues found. | 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 jl_gc_free_memory from gc-stock.c as the stock GC updates the
// information in the global variable gc_heap_stats (which is specific to the stock GC)
static void jl_gc_free_memory(jl_genericmemory_t *m, int isaligned) JL_NOTSAFEPOINT
{
assert(jl_is_genericmemory(m));
assert(jl_genericmemory_how(m) == 1 ... | No issues found. | // from jl_gc_free_memory from gc-stock.c as the stock GC updates the
// information in the global variable gc_heap_stats (which is specific to the stock GC)
static void jl_gc_free_memory(jl_genericmemory_t *m, int isaligned) JL_NOTSAFEPOINT
{
assert(jl_is_genericmemory(m));
assert(jl_genericmemory_how(m) == 1 ... | @@ -337,6 +337,18 @@ JL_DLLEXPORT const char* jl_gc_active_impl(void) {
return mmtk_version;
}
+JL_DLLEXPORT int jl_gc_enable_auto_full_collection(int on)
+{
+ // MMTk does not currently support collection type control
+ return 1;
+}
+
+JL_DLLEXPORT int jl_gc_auto_full_collection_is_enabled(void)
+{
+ ... | src/gc-mmtk.c | 0 | C | 1 | none | 16 | 51 | 51 | true | Add API to disable full collections | 61,087 | JuliaLang/julia | 35,573 | Julia | gbaraldi | Review this pull request change.
Language: C
File: src/gc-mmtk.c
PR Title: Add API to disable full collections
BEFORE CODE: // from jl_gc_free_memory from gc-stock.c as the stock GC updates the
// information in the global variable gc_heap_stats (which is specific to the stock GC)
static void jl_gc_free_memory(jl_g... | No issues found. | 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. | |
static jl_cgval_t emit_atomicfence(jl_codectx_t &ctx, ArrayRef<jl_cgval_t> argv)
{
const jl_cgval_t &ord = argv[0];
const jl_cgval_t &ssid_arg = argv[1];
llvm::SyncScope::ID ssid = llvm::SyncScope::System;
if (!ssid_arg.constant || !jl_is_symbol(ssid_arg.constant) ||
((jl_sym_t*)ssid_arg.constan... | No issues found. | static jl_cgval_t emit_atomicfence(jl_codectx_t &ctx, ArrayRef<jl_cgval_t> argv)
{
const jl_cgval_t &ord = argv[0];
const jl_cgval_t &ssid_arg = argv[1];
llvm::SyncScope::ID ssid = llvm::SyncScope::System;
if (!ssid_arg.constant || !jl_is_symbol(ssid_arg.constant) ||
((jl_sym_t*)ssid_arg.constan... | @@ -863,17 +863,17 @@ static jl_cgval_t emit_pointerset(jl_codectx_t &ctx, ArrayRef<jl_cgval_t> argv)
jl_aliasinfo_t ai = jl_aliasinfo_t::fromTBAA(ctx, ctx.tbaa().tbaa_data);
ai.decorateInst(store);
}
- else if (!x.inline_roots.empty()) {
- recombine_value(ctx, e, thePtr, jl_aliasinfo_t... | src/intrinsics.cpp | 0 | C++ | 1 | none | 16 | 51 | 51 | true | fix pointerset for values with inline_roots | 61,105 | JuliaLang/julia | 35,573 | Julia | adienes | Review this pull request change.
Language: C++
File: src/intrinsics.cpp
PR Title: fix pointerset for values with inline_roots
BEFORE CODE: static jl_cgval_t emit_atomicfence(jl_codectx_t &ctx, ArrayRef<jl_cgval_t> argv)
{
const jl_cgval_t &ord = argv[0];
const jl_cgval_t &ssid_arg = argv[1];
llvm::SyncS... | No issues found. | 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. | |
binfo.is_always_defined && print(io, ", is_always_defined=true")
binfo.is_used_undef && print(io, ", is_used_undef=true")
print(io, ")")
end
"""
Metadata about "entities" (variables, constants, etc) in the program. Each
entity is associated to a unique integer id, the BindingId. A binding will be
inf... | No issues found. | binfo.is_always_defined && print(io, ", is_always_defined=true")
binfo.is_used_undef && print(io, ", is_used_undef=true")
print(io, ")")
end
"""
Metadata about "entities" (variables, constants, etc) in the program. Each
entity is associated to a unique integer id, the BindingId. A binding will be
inf... | @@ -13,12 +13,13 @@ mutable struct BindingInfo
is_ssa::Bool # Single assignment, defined before use
is_internal::Bool # True for internal bindings generated by the compiler
is_ambiguous_local::Bool # Local, but would be global in soft scope (ie, the REPL)
+ unboxed::Bool # determ... | JuliaLowering/src/bindings.jl | 0 | Julia | 1 | none | 16 | 51 | 51 | true | [JuliaLowering] Don't clobber `is_always_defined` in unboxing | 61,134 | JuliaLang/julia | 35,573 | Julia | mlechu | Review this pull request change.
Language: Julia
File: JuliaLowering/src/bindings.jl
PR Title: [JuliaLowering] Don't clobber `is_always_defined` in unboxing
BEFORE CODE: binfo.is_always_defined && print(io, ", is_always_defined=true")
binfo.is_used_undef && print(io, ", is_used_undef=true")
print(... | No issues found. | 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 NPM;
}
};
template<size_t N>
struct sizedOptimizerT {
sizedOptimizerT(TargetMachine &TM, SmallVector<std::function<void()>, 0> &printers, std::mutex &llvm_printing_mutex) JL_NOTSAFEPOINT {
for (size_t i = 0; i < N; i++) {
PMs[i] =... | No issues found. | }
return NPM;
}
};
template<size_t N>
struct sizedOptimizerT {
sizedOptimizerT(TargetMachine &TM, SmallVector<std::function<void()>, 0> &printers, std::mutex &llvm_printing_mutex) JL_NOTSAFEPOINT {
for (size_t i = 0; i < N; i++) {
PMs[i] =... | @@ -369,12 +369,10 @@ void *jl_jit_abi_converter_impl(jl_task_t *ct, jl_abi_t from_abi,
gf_thunk_name = emit_abi_dispatcher(*out, from_abi, codeinst, llvminvoke);
}
}
- int8_t gc_state = jl_gc_safe_enter(ct->ptls);
auto &ES = jl_ExecutionEngine->getExecutionSession();
auto emitte... | src/jitlayers.cpp | 0 | C++ | 1 | none | 16 | 51 | 51 | true | Local names linking fixes | 61,165 | JuliaLang/julia | 35,573 | Julia | xal-0 | Review this pull request change.
Language: C++
File: src/jitlayers.cpp
PR Title: Local names linking fixes
BEFORE CODE: }
return NPM;
}
};
template<size_t N>
struct sizedOptimizerT {
sizedOptimizerT(TargetMachine &TM, SmallVector<std::function<void()>, 0> &printe... | No issues found. | 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. | |
@ast ctx arg_sym arg_sym=>K"Identifier"
else
setmeta!(newsym(ctx, arg_sym, "#arg$(string(arg_id))#"),
:nospecialize, getmeta(arg_sym, :nospecialize, false))
end
else
@chk kind(arg_sym) in KSet"Identifier BindingId"
name = arg_sym
end
... | No issues found. | @ast ctx arg_sym arg_sym=>K"Identifier"
else
setmeta!(newsym(ctx, arg_sym, "#arg$(string(arg_id))#"),
:nospecialize, getmeta(arg_sym, :nospecialize, false))
end
else
@chk kind(arg_sym) in KSet"Identifier BindingId"
name = arg_sym
end
... | @@ -2038,7 +2038,7 @@ function expand_for(ctx, ex)
body = if i == numchildren(iterspecs)
# Innermost loop gets the continue label and copied vars
@ast ctx ex [K"symbolicblock"
- "loop_cont"::K"symboliclabel"
+ "loop-cont"::K"symboliclabel"
... | JuliaLowering/src/desugaring.jl | 0 | Julia | 1 | none | 16 | 51 | 51 | true | [JuliaLowering] Misc. cleanup: `symboliclabel`, `flatten_blocks` | 61,166 | JuliaLang/julia | 35,573 | Julia | mlechu | Review this pull request change.
Language: Julia
File: JuliaLowering/src/desugaring.jl
PR Title: [JuliaLowering] Misc. cleanup: `symboliclabel`, `flatten_blocks`
BEFORE CODE: @ast ctx arg_sym arg_sym=>K"Identifier"
else
setmeta!(newsym(ctx, arg_sym, "#arg$(string(arg_id))#"),
... | No issues found. | 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. | |
@test jltestset isa Test.AbstractTestSet
@test jltestset.n_passed == 1
end
end
@testset "macros producing meta forms" begin
function find_method_ci(thunk)
ci = thunk.args[1]::Core.CodeInfo
m = findfirst(x->(x isa Expr && x.head === :method && length(x.args) === 3), ci.code)
... | No issues found. | @test jltestset isa Test.AbstractTestSet
@test jltestset.n_passed == 1
end
end
@testset "macros producing meta forms" begin
function find_method_ci(thunk)
ci = thunk.args[1]::Core.CodeInfo
m = findfirst(x->(x isa Expr && x.head === :method && length(x.args) === 3), ci.code)
... | @@ -866,4 +866,22 @@ end
"""; expr_compat_mode=true)
end
+@testset "macro source LineNumberNode" begin
+ Base.include_string(test_mod, raw"""
+ macro srcfile()
+ string(__source__.file)
+ end
+ """)
+
+ mac_ex = Expr(:macrocall, Symbol("@srcfile"), LineNumberNode(1, "goodfile"))
+ mac_s... | JuliaLowering/test/macros.jl | 0 | Julia | 1 | none | 16 | 51 | 51 | true | [JuliaLowering] Take macro lno from argument, not provenance | 61,178 | JuliaLang/julia | 35,573 | Julia | mlechu | Review this pull request change.
Language: Julia
File: JuliaLowering/test/macros.jl
PR Title: [JuliaLowering] Take macro lno from argument, not provenance
BEFORE CODE: @test jltestset isa Test.AbstractTestSet
@test jltestset.n_passed == 1
end
end
@testset "macros producing meta forms" begin
... | No issues found. | 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. | |
});
}
currentColumn.index += 1;
}
setVariable(name, value) {
let variableName = name;
const vars = this.engine.referenceData.variables;
if (name.startsWith('$push:')) {
const { 1: varName } = name.split('$push:');
if (!objectHasKey(vars, varName)) vars[varName] = [];
... | My workflow keeps running repeatedly while it should be once per day (by checking variables in workflow). Then I found in Storage tab, the variables are prefixed with duplicated "$$". So, I guess this is the cause.
In previous code, the variable's name was sliced: https://github.com/AutomaApp/automa/pull/1522/files#... | });
}
currentColumn.index += 1;
}
setVariable(name, value) {
let variableName = name;
const vars = this.engine.referenceData.variables;
if (name.startsWith('$push:')) {
const { 1: varName } = name.split('$push:');
if (!objectHasKey(vars, varName)) vars[varName] = [];
... | @@ -119,9 +121,18 @@ class WorkflowWorker {
else if (!Array.isArray(vars[varName])) vars[varName] = [vars[varName]];
vars[varName].push(value);
+ variableName = varName;
+ } else {
+ vars[name] = value;
+ }
+
+ if (variableName.startsWith('$$')) {
+ dbStorage.variables.put({
+ ... | src/workflowEngine/WorkflowWorker.js | 26 | JavaScript | 0.5 | refactor | 393 | 51 | 51 | false | v1.28.21 | 1,522 | Kholid060/automa | 2,360 | Vue | UnluckyNinja | Kholid060 | Review this pull request change.
Language: JavaScript
File: src/workflowEngine/WorkflowWorker.js
PR Title: v1.28.21
BEFORE CODE: });
}
currentColumn.index += 1;
}
setVariable(name, value) {
let variableName = name;
const vars = this.engine.referenceData.variables;
if (name.startsWit... | My workflow keeps running repeatedly while it should be once per day (by checking variables in workflow). Then I found in Storage tab, the variables are prefixed with duplicated "$$". So, I guess this is the cause.
In previous code, the variable's name was sliced: https://github.com/AutomaApp/automa/pull/1522/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. |
if (dir === 'up') {
const parentEl = element.parentElement;
if (!parentEl) return null;
const scrollableElement = findScrollableElement(
parentEl,
dir,
maxDepth - 1
);
if (scrollableElement) return scrollableElement;
} else {
for (let index = 0; index < element.childEleme... | No issues found. |
if (dir === 'up') {
const parentEl = element.parentElement;
if (!parentEl) return null;
const scrollableElement = findScrollableElement(
parentEl,
dir,
maxDepth - 1
);
if (scrollableElement) return scrollableElement;
} else {
for (let index = 0; index < element.childEleme... | @@ -1,5 +1,54 @@
import handleSelector from '../handleSelector';
+function isElScrollable(element) {
+ const excludedTags = ['SCRIPT', 'STYLE', 'SVG', 'HEAD'];
+
+ const isOverflow = /scroll|auto/.test(getComputedStyle(element).overflow);
+ const isScrollable =
+ element.scrollHeight > element.clientHeight ||
... | src/content/blocksHandler/handlerElementScroll.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | v1.28.21 | 1,522 | Kholid060/automa | 2,360 | Vue | Kholid060 | Review this pull request change.
Language: JavaScript
File: src/content/blocksHandler/handlerElementScroll.js
PR Title: v1.28.21
BEFORE CODE:
if (dir === 'up') {
const parentEl = element.parentElement;
if (!parentEl) return null;
const scrollableElement = findScrollableElement(
parentEl,
... | No issues found. | 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. | |
#!/bin/sh
mkdir "~test"
failed=
for dir in *; do
p="${dir}/test.txt"
if [ -d "${dir}" ] && [ -f "${p}" ]; then
echo "Testing '${dir}'"
bin_path="~test/${dir}"
hvm compile "${dir}/main.hvm"
clang -O2 "./${dir}/main.c" -o "${bin_path}" -lpthread
while read -r line; do
IFS=' ' read -ra... | I don't think it's a good idea to use `sh` instead of `bash` for the shebang here since this script uses bashisms and isn't POSIX compliant. | #!/bin/bash
mkdir "~test"
failed=
for dir in *; do
p="${dir}/test.txt"
if [ -d "${dir}" ] && [ -f "${p}" ]; then
echo "Testing '${dir}'"
bin_path="~test/${dir}"
hvm compile "${dir}/main.hvm"
clang -O2 "./${dir}/main.c" -o "${bin_path}" -lpthread
while read -r line; do
IFS=' ' read -... | @@ -1,4 +1,4 @@
-#!/bin/bash
+#!/bin/sh | bench/test.sh | 1 | Shell | 0.571 | suggestion | 140 | 26 | 26 | false | Clean up more | 78 | Kindelia/HVM | 4,376 | Cuda | nothingnesses | azdavis | Review this pull request change.
Language: Shell
File: bench/test.sh
PR Title: Clean up more
BEFORE CODE: #!/bin/sh
mkdir "~test"
failed=
for dir in *; do
p="${dir}/test.txt"
if [ -d "${dir}" ] && [ -f "${p}" ]; then
echo "Testing '${dir}'"
bin_path="~test/${dir}"
hvm compile "${dir}/main.hvm"... | I don't think it's a good idea to use `sh` instead of `bash` for the shebang here since this script uses bashisms and isn't POSIX compliant. | 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. |
mod builder;
mod compiler;
mod language;
mod parser;
mod readback;
mod rulebook;
mod runtime;
use clap::{Parser, Subcommand};
#[derive(Parser)]
#[clap(author, version, about, long_about = None)]
#[clap(propagate_version = true)]
pub struct Cli {
#[clap(subcommand)]
pub command: Command,
}
#[derive(Subcommand)]
p... | The cargo linter was annoyed ... I normally don't include things like this in my PRs, but I like to have a happy-ish baseline. | mod builder;
mod compiler;
mod language;
mod parser;
mod readback;
mod rulebook;
mod runtime;
use clap::{Parser, Subcommand};
#[derive(Parser)]
#[clap(author, version, about, long_about = None)]
#[clap(propagate_version = true)]
pub struct Cli {
#[clap(subcommand)]
pub command: Command,
}
#[derive(Subcommand)]
p... | @@ -19,10 +19,7 @@ pub struct Cli {
#[derive(Subcommand)]
pub enum Command {
#[clap(about = "Run a file interpreted", name = "run", aliases = &["r"])]
- Run { | src/main.rs | 22 | Rust | 0.357 | style | 126 | 47 | 47 | false | Spelling | 113 | Kindelia/HVM | 4,376 | Cuda | jsoref | jsoref | Review this pull request change.
Language: Rust
File: src/main.rs
PR Title: Spelling
BEFORE CODE: mod builder;
mod compiler;
mod language;
mod parser;
mod readback;
mod rulebook;
mod runtime;
use clap::{Parser, Subcommand};
#[derive(Parser)]
#[clap(author, version, about, long_about = None)]
#[clap(propagate_vers... | The cargo linter was annoyed ... I normally don't include things like this in my PRs, but I like to have a happy-ish baseline. | 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. |
match cc::Build::new()
.file("src/hvm.c")
.opt_level(3)
.warnings(false)
.define("TPC_L2", &*tpcl2.to_string())
.try_compile("hvm-c") {
Ok(_) => println!("cargo:rustc-cfg=feature=\"c\""),
Err(e) => {
println!("cargo:warning=\x1b[1m\x1b[31mWARNING: Failed to compile hvm.c:\x... | ```suggestion
```
shouldn't this be removed then, since it is supposed to be acknowledged and fixed? | .file("src/hvm.c")
.opt_level(3)
.warnings(false)
.define("TPC_L2", &*tpcl2.to_string())
.try_compile("hvm-c") {
Ok(_) => println!("cargo:rustc-cfg=feature=\"c\""),
Err(e) => {
println!("cargo:warning=\x1b[1m\x1b[31mWARNING: Failed to compile hvm.c:\x1b[0m {}", e);
prin... | @@ -31,14 +29,14 @@ fn main() {
cc::Build::new()
.cuda(true)
.file("src/hvm.cu")
- .flag("-diag-suppress=177")
- .flag("-diag-suppress=550")
- .flag("-diag-suppress=20039")
+ .flag("-diag-suppress=177") // variable was declared but never referenced
+ .flag("-diag-suppress=550... | build.rs | 26 | Rust | 0.786 | question | 104 | 37 | 35 | false | add cuda warning comments | 323 | Kindelia/HVM | 4,376 | Cuda | kings177 | enricozb | Review this pull request change.
Language: Rust
File: build.rs
PR Title: add cuda warning comments
BEFORE CODE: match cc::Build::new()
.file("src/hvm.c")
.opt_level(3)
.warnings(false)
.define("TPC_L2", &*tpcl2.to_string())
.try_compile("hvm-c") {
Ok(_) => println!("cargo:rustc-c... | ```suggestion
```
shouldn't this be removed then, since it is supposed to be acknowledged and fixed? | 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.rbag[index] = rx;
}
}
}
impl Book {
pub fn parse(code: &str) -> Result<Self, String> {
CoreParser::new(code).parse_book()
}
pub fn build(&self) -> hvm::Book {
let mut name_to_fid = BTreeMap::new();
let mut fid_to_name = BTreeMap::new();
fid_to_name.insert(0, "main".to_string());
... | maybe just `expect` instead of `let .. else`? | def.rbag[index] = rx;
}
}
}
impl Book {
pub fn parse(code: &str) -> Result<Self, String> {
CoreParser::new(code).parse_book()
}
pub fn build(&self) -> hvm::Book {
let mut name_to_fid = BTreeMap::new();
let mut fid_to_name = BTreeMap::new();
fid_to_name.insert(0, "main".to_string());
... | @@ -505,18 +505,19 @@ impl Book {
}
let mut book = hvm::Book { defs: Vec::new() };
for (fid, name) in &fid_to_name {
- if let Some(ast_def) = self.defs.get(name) {
- let mut def = hvm::Def {
- name: name.clone(),
- safe: true,
- root: hvm::Port(0),
- rbag: ... | src/ast.rs | 26 | Rust | 0.286 | question | 45 | 41 | 39 | false | error gracefully when `@main` is missing | 346 | Kindelia/HVM | 4,376 | Cuda | enricozb | tjjfvi | Review this pull request change.
Language: Rust
File: src/ast.rs
PR Title: error gracefully when `@main` is missing
BEFORE CODE: def.rbag[index] = rx;
}
}
}
impl Book {
pub fn parse(code: &str) -> Result<Self, String> {
CoreParser::new(code).parse_book()
}
pub fn build(&self) -> hvm::Book {
... | maybe just `expect` instead of `let .. 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. |
// Top-Level Definition
struct Def {
char name[256];
bool safe;
u32 rbag_len;
u32 node_len;
u32 vars_len;
Port root;
Pair rbag_buf[L_NODE_LEN/TPB];
Pair node_buf[L_NODE_LEN/TPB];
};
typedef struct Book Book;
// A Foreign Function
typedef struct {
char name[256];
Port (*func)(GNet*, Port);
} FFn... | these sizes look right. defs are larger than fns. why same size? | // Top-Level Definition
struct Def {
char name[256];
bool safe;
u32 rbag_len;
u32 node_len;
u32 vars_len;
Port root;
Pair rbag_buf[L_NODE_LEN/TPB];
Pair node_buf[L_NODE_LEN/TPB];
};
typedef struct Book Book;
// A Foreign Function
typedef struct {
char name[256];
Port (*func)(GNet*, Port);
} FFn... | @@ -195,10 +195,20 @@ struct Def {
Pair node_buf[L_NODE_LEN/TPB];
};
+typedef struct Book Book;
+
+// A Foreign Function
+typedef struct {
+ char name[256];
+ Port (*func)(GNet*, Port);
+} FFn;
+
// Book of Definitions
struct Book {
u32 defs_len;
Def defs_buf[0x4000]; // 256 MB
+ u32 ffns_len;
+ FFn f... | src/hvm.cu | 26 | CUDA | 0.214 | question | 64 | 51 | 51 | false | CUDA Basic IO | 347 | Kindelia/HVM | 4,376 | Cuda | VictorTaelin | enricozb | Review this pull request change.
Language: CUDA
File: src/hvm.cu
PR Title: CUDA Basic IO
BEFORE CODE: // Top-Level Definition
struct Def {
char name[256];
bool safe;
u32 rbag_len;
u32 node_len;
u32 vars_len;
Port root;
Pair rbag_buf[L_NODE_LEN/TPB];
Pair node_buf[L_NODE_LEN/TPB];
};
typedef stru... | these sizes look right. defs are larger than fns. why same size? | 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 (get_tag(lam_port) != CON) return ctr;
Pair lam_node = gnet_node_load(gnet, get_val(lam_port));
// Loads first application
Port app_port = gnet_expand(gnet, get_fst(lam_node));
if (get_tag(app_port) != CON) return ctr;
Pair app_node = gnet_node_load(gnet, get_val(app_port));
// Loads first argument (... | strings in hvm are actually just lists of unicode codepoints, we must update that | if (get_tag(lam_port) != CON) return ctr;
Pair lam_node = gnet_node_load(gnet, get_val(lam_port));
// Loads first application
Port app_port = gnet_expand(gnet, get_fst(lam_node));
if (get_tag(app_port) != CON) return ctr;
Pair app_node = gnet_node_load(gnet, get_val(app_port));
// Loads first argument (... | @@ -1802,16 +1827,229 @@ Port gnet_expand(GNet* gnet, Port port) {
Port gnet_make_node(GNet* gnet, Tag tag, Port fst, Port snd) {
Port ret;
Port* d_ret;
- cudaMalloc(&d_ret, sizeof(Port));
+ cudaMalloc(&d_ret, sizeof(Port));
make_node<<<1,1>>>(gnet, tag, fst, snd, d_ret);
cudaMemcpy(&ret, d_ret, sizeof(... | src/hvm.cu | 26 | CUDA | 0.214 | suggestion | 82 | 51 | 51 | false | CUDA Basic IO | 347 | Kindelia/HVM | 4,376 | Cuda | VictorTaelin | enricozb | Review this pull request change.
Language: CUDA
File: src/hvm.cu
PR Title: CUDA Basic IO
BEFORE CODE: if (get_tag(lam_port) != CON) return ctr;
Pair lam_node = gnet_node_load(gnet, get_val(lam_port));
// Loads first application
Port app_port = gnet_expand(gnet, get_fst(lam_node));
if (get_tag(app_port) !... | strings in hvm are actually just lists of unicode codepoints, we must update that | 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. |
pub fn is_cast(&self) -> bool {
self.get_typ() == TY_SYM && self.get_sym() >= TY_U24 && self.get_sym() <= TY_F24
}
// Partial application.
pub fn partial(a: Self, b: Self) -> Self {
Numb((b.0 & !0x1F) | a.get_sym() as u32)
}
// Cast a number to another type.
// The semantics are meant to spiritu... | might it be somewhat more efficient to clamp it as an integer? not that it matters much | pub fn is_num(&self) -> bool {
self.get_typ() >= TY_U24 && self.get_typ() <= TY_F24
}
pub fn is_cast(&self) -> bool {
self.get_typ() == TY_SYM && self.get_sym() >= TY_U24 && self.get_sym() <= TY_F24
}
// Partial application.
pub fn partial(a: Self, b: Self) -> Self {
Numb((b.0 & !0x1F) | a.get... | @@ -266,16 +266,47 @@ impl Numb {
}
// Gets the numeric type.
-
pub fn get_typ(&self) -> Tag {
- return (self.0 & 0x1F) as Tag;
+ (self.0 & 0x1F) as Tag
+ }
+
+ pub fn is_num(&self) -> bool {
+ self.get_typ() >= TY_U24 && self.get_typ() <= TY_F24
}
- // Flip flag.
+ pub fn is_cast(&self) ->... | src/hvm.rs | 26 | Rust | 0.214 | performance | 87 | 51 | 51 | false | Numeric Casting Operations | 361 | Kindelia/HVM | 4,376 | Cuda | tjjfvi | enricozb | Review this pull request change.
Language: Rust
File: src/hvm.rs
PR Title: Numeric Casting Operations
BEFORE CODE: pub fn is_cast(&self) -> bool {
self.get_typ() == TY_SYM && self.get_sym() >= TY_U24 && self.get_sym() <= TY_F24
}
// Partial application.
pub fn partial(a: Self, b: Self) -> Self {
Nu... | might it be somewhat more efficient to clamp it as an integer? not that it matters 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. |
pub fn is_num(&self) -> bool {
self.get_typ() >= TY_U24 && self.get_typ() <= TY_F24
}
pub fn is_cast(&self) -> bool {
self.get_typ() == TY_SYM && self.get_sym() >= TY_U24 && self.get_sym() <= TY_F24
}
// Partial application.
pub fn partial(a: Self, b: Self) -> Self {
Numb((b.0 & !0x1F) | a.get... | maybe extract these numbers to constants? if they were clamped as integers you could have `const U24_MAX = 1 << 24 - 1;` | pub fn get_typ(&self) -> Tag {
(self.0 & 0x1F) as Tag
}
pub fn is_num(&self) -> bool {
self.get_typ() >= TY_U24 && self.get_typ() <= TY_F24
}
pub fn is_cast(&self) -> bool {
self.get_typ() == TY_SYM && self.get_sym() >= TY_U24 && self.get_sym() <= TY_F24
}
// Partial application.
pub fn p... | @@ -266,16 +266,47 @@ impl Numb {
}
// Gets the numeric type.
-
pub fn get_typ(&self) -> Tag {
- return (self.0 & 0x1F) as Tag;
+ (self.0 & 0x1F) as Tag
+ }
+
+ pub fn is_num(&self) -> bool {
+ self.get_typ() >= TY_U24 && self.get_typ() <= TY_F24
}
- // Flip flag.
+ pub fn is_cast(&self) ->... | src/hvm.rs | 26 | Rust | 0.571 | refactor | 121 | 51 | 51 | false | Numeric Casting Operations | 361 | Kindelia/HVM | 4,376 | Cuda | tjjfvi | enricozb | Review this pull request change.
Language: Rust
File: src/hvm.rs
PR Title: Numeric Casting Operations
BEFORE CODE: pub fn is_num(&self) -> bool {
self.get_typ() >= TY_U24 && self.get_typ() <= TY_F24
}
pub fn is_cast(&self) -> bool {
self.get_typ() == TY_SYM && self.get_sym() >= TY_U24 && self.get_sym... | maybe extract these numbers to constants? if they were clamped as integers you could have `const U24_MAX = 1 << 24 - 1;` | 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.node[index] = hvm::Pair::new(p1, p2);
return hvm::Port::new(hvm::OPR, index as hvm::Val);
},
Tree::Swi { fst, snd } => {
let index = def.node.len();
def.node.push(hvm::Pair(0));
let p1 = fst.build(def, fids, vars);
let p2 = snd.build(def, fids, vars);
... | Writing a recursive function like this may not be the best idea since we still don't have a way to increase stack size as needed like in the `hvm-64` repo. I think it's fine for now to add this function like this, since pretty much all the other functions related to trees are also recursive and if this one fails, they ... | def.node[index] = hvm::Pair::new(p1, p2);
return hvm::Port::new(hvm::OPR, index as hvm::Val);
},
Tree::Swi { fst, snd } => {
let index = def.node.len();
def.node.push(hvm::Pair(0));
let p1 = fst.build(def, fids, vars);
let p2 = snd.build(def, fids, vars);
... | @@ -488,6 +489,19 @@ impl Tree {
},
}
}
+
+ pub fn direct_dependencies<'name>(&'name self) -> BTreeSet<&'name str> {
+ match self {
+ Tree::Ref { nam } => BTreeSet::from([nam.as_str()]),
+ Tree::Con { fst, snd } => &fst.direct_dependencies() | &snd.direct_dependencies(),
+ Tree::Dup { ... | src/ast.rs | 26 | Rust | 0.571 | bug | 327 | 51 | 51 | false | Propagate unsafety to definitions that depend on unsafe definitions | 379 | Kindelia/HVM | 4,376 | Cuda | edusporto | edusporto | Review this pull request change.
Language: Rust
File: src/ast.rs
PR Title: Propagate unsafety to definitions that depend on unsafe definitions
BEFORE CODE: def.node[index] = hvm::Pair::new(p1, p2);
return hvm::Port::new(hvm::OPR, index as hvm::Val);
},
Tree::Swi { fst, snd } => {
... | Writing a recursive function like this may not be the best idea since we still don't have a way to increase stack size as needed like in the `hvm-64` repo. I think it's fine for now to add this function like this, since pretty much all the other functions related to trees are also recursive and if this one fails, they ... | 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. |
let p2 = snd.build(def, fids, vars);
let rx = hvm::Pair::new(p1, p2);
let rx = if *par { rx.set_par_flag() } else { rx };
def.rbag[index] = rx;
}
}
}
impl Book {
pub fn parse(code: &str) -> Result<Self, String> {
CoreParser::new(code).parse_book()
}
pub fn build(&self) -> hvm::... | isn't this duplicative of `name_to_fid`? | let index = def.node.len();
def.root = self.root.build(def, fids, vars);
for (par, fst, snd) in &self.rbag {
let index = def.rbag.len();
def.rbag.push(hvm::Pair(0));
let p1 = fst.build(def, fids, vars);
let p2 = snd.build(def, fids, vars);
let rx = hvm::Pair::new(p1, p2);
... | @@ -523,6 +537,7 @@ impl Book {
}
}
let mut book = hvm::Book { defs: Vec::new() };
+ let mut lookup = BTreeMap::new(); | src/ast.rs | 26 | Rust | 0.214 | question | 40 | 51 | 51 | false | Propagate unsafety to definitions that depend on unsafe definitions | 379 | Kindelia/HVM | 4,376 | Cuda | tjjfvi | edusporto | Review this pull request change.
Language: Rust
File: src/ast.rs
PR Title: Propagate unsafety to definitions that depend on unsafe definitions
BEFORE CODE: let p2 = snd.build(def, fids, vars);
let rx = hvm::Pair::new(p1, p2);
let rx = if *par { rx.set_par_flag() } else { rx };
def.rbag[index... | isn't this duplicative of `name_to_fid`? | 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. |
/// that is, if definition `A` requires `B`, `B: A` is in the return map.
/// This is used to propagate unsafe definitions to others that depend on them.
///
/// This solution has linear complexity on the number of definitions in the
/// book and the number of direct references in each definition, but it als... | ```suggestion
result
.get_mut()
.expect("global definition depends on undeclared reference")
.insert(name);
``` | }
}
}
/// Calculates the dependents of each definition, that is, if definition `A`
/// requires `B`, `B: A` is in the return map. This is used to propagate unsafe
/// definitions to others that depend on them.
///
/// This solution has linear complexity on the number of definitions in the
/// ... | @@ -535,7 +550,86 @@ impl Book {
};
ast_def.build(&mut def, &name_to_fid, &mut BTreeMap::new());
book.defs.push(def);
+ lookup.insert(name.clone(), book.defs.len() - 1);
}
+ self.propagate_safety(&mut book, &lookup);
return book;
}
+
+ /// Propagate unsafe definitions to those... | src/ast.rs | 26 | Rust | 0.714 | suggestion | 154 | 40 | 42 | false | Propagate unsafety to definitions that depend on unsafe definitions | 379 | Kindelia/HVM | 4,376 | Cuda | tjjfvi | edusporto | Review this pull request change.
Language: Rust
File: src/ast.rs
PR Title: Propagate unsafety to definitions that depend on unsafe definitions
BEFORE CODE: /// that is, if definition `A` requires `B`, `B: A` is in the return map.
/// This is used to propagate unsafe definitions to others that depend on them.
... | ```suggestion
result
.get_mut()
.expect("global definition depends on undeclared reference")
.insert(name);
``` | 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. |
///
/// When calling this function, it is expected that definitions that are directly
/// unsafe are already marked as such in the `compiled_book`.
///
/// This does not completely solve the cloning safety in HVM. It only stops invalid
/// **global** definitions from being cloned, but local unsafe code can... | ```suggestion
if !visited.insert(curr) {
continue;
}
``` | return book;
}
/// Propagate unsafe definitions to those that reference them.
///
/// When calling this function, it is expected that definitions that are directly
/// unsafe are already marked as such in the `compiled_book`.
///
/// This does not completely solve the cloning safety in HVM. It only ... | @@ -535,7 +550,86 @@ impl Book {
};
ast_def.build(&mut def, &name_to_fid, &mut BTreeMap::new());
book.defs.push(def);
+ lookup.insert(name.clone(), book.defs.len() - 1);
}
+ self.propagate_safety(&mut book, &lookup);
return book;
}
+
+ /// Propagate unsafe definitions to those... | src/ast.rs | 26 | Rust | 0.571 | suggestion | 80 | 51 | 51 | false | Propagate unsafety to definitions that depend on unsafe definitions | 379 | Kindelia/HVM | 4,376 | Cuda | tjjfvi | edusporto | Review this pull request change.
Language: Rust
File: src/ast.rs
PR Title: Propagate unsafety to definitions that depend on unsafe definitions
BEFORE CODE: ///
/// When calling this function, it is expected that definitions that are directly
/// unsafe are already marked as such in the `compiled_book`.
/// ... | ```suggestion
if !visited.insert(curr) {
continue;
}
``` | 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: name.clone(),
safe: true,
root: hvm::Port(0),
rbag: vec![],
node: vec![],
vars: 0,
};
ast_def.build(&mut def, &name_to_fid, &mut BTreeMap::new());
book.defs.push(def);
}
self.propagate_safety(&mut book, &name_to_fid);
return book;
}
... | ```suggestion
let dependents = self.direct_dependents();
``` | name: name.clone(),
safe: true,
root: hvm::Port(0),
rbag: vec![],
node: vec![],
vars: 0,
};
ast_def.build(&mut def, &name_to_fid, &mut BTreeMap::new());
book.defs.push(def);
}
self.propagate_safety(&mut book, &name_to_fid);
return book;
}
... | @@ -536,6 +556,82 @@ impl Book {
ast_def.build(&mut def, &name_to_fid, &mut BTreeMap::new());
book.defs.push(def);
}
+ self.propagate_safety(&mut book, &name_to_fid);
return book;
}
+
+ /// Propagate unsafe definitions to those that reference them.
+ ///
+ /// When calling this function... | src/ast.rs | 26 | Rust | 0.571 | suggestion | 66 | 51 | 51 | false | Propagate unsafety to definitions that depend on unsafe definitions | 379 | Kindelia/HVM | 4,376 | Cuda | tjjfvi | edusporto | Review this pull request change.
Language: Rust
File: src/ast.rs
PR Title: Propagate unsafety to definitions that depend on unsafe definitions
BEFORE CODE: name: name.clone(),
safe: true,
root: hvm::Port(0),
rbag: vec![],
node: vec![],
vars: 0,
};
ast_def.... | ```suggestion
let dependents = self.direct_dependents();
``` | 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. |
case OP_OR: return new_i24(av | bv);
case OP_XOR: return new_i24(av ^ bv);
default: return new_i24(0);
}
}
case TY_F24: {
float av = get_f24(a);
float bv = get_f24(b);
switch (op) {
case OP_ADD: return new_f24(av + bv);
case OP_SUB: return new... | We don't need to waste f24 FP_SHL and FP_SHR here | case OP_OR: return new_i24(av | bv);
case OP_XOR: return new_i24(av ^ bv);
default: return new_i24(0);
}
}
case TY_F24: {
float av = get_f24(a);
float bv = get_f24(b);
switch (op) {
case OP_ADD: return new_f24(av + bv);
case OP_SUB: return new... | @@ -570,6 +570,10 @@ static inline Numb operate(Numb a, Numb b) {
case OP_AND: return new_f24(atan2f(av, bv));
case OP_OR: return new_f24(logf(bv) / logf(av));
case OP_XOR: return new_f24(powf(av, bv));
+ case OP_SHL: return new_f24(sin(av + bv));
+ case FP_SHL: return new_f24(... | src/hvm.c | 26 | C | 0.071 | suggestion | 49 | 51 | 51 | false | tan + sin funcs | 391 | Kindelia/HVM | 4,376 | Cuda | nicolas-abril | enricozb | Review this pull request change.
Language: C
File: src/hvm.c
PR Title: tan + sin funcs
BEFORE CODE: case OP_OR: return new_i24(av | bv);
case OP_XOR: return new_i24(av ^ bv);
default: return new_i24(0);
}
}
case TY_F24: {
float av = get_f24(a);
float bv = get_f... | We don't need to waste f24 FP_SHL and FP_SHR 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 Ok(Numb(hvm::Numb::new_sym(cast).0));
}
// Parses the symbol
let op = hvm::Numb::new_sym(match () {
// numeric operations
_ if self.try_consume("+") => hvm::OP_ADD,
_ if self.try_consume("-") => hvm::OP_SUB,
_ if self.try_consume(":-") => hvm::FP_SUB,
_ if se... | These symbols are trying to uniquely map to operators, so we shouldn't add sin and tan here. Notice how there's no pow, log and atan2. | return Ok(Numb(hvm::Numb::new_sym(cast).0));
}
// Parses the symbol
let op = hvm::Numb::new_sym(match () {
// numeric operations
_ if self.try_consume("+") => hvm::OP_ADD,
_ if self.try_consume("-") => hvm::OP_SUB,
_ if self.try_consume(":-") => hvm::FP_SUB,
_ if se... | @@ -79,6 +79,8 @@ impl<'i> CoreParser<'i> {
_ if self.try_consume("&") => hvm::OP_AND,
_ if self.try_consume("|") => hvm::OP_OR,
_ if self.try_consume("^") => hvm::OP_XOR,
+ _ if self.try_consume("sin") => hvm::OP_SHL, | src/ast.rs | 26 | Rust | 0.429 | suggestion | 134 | 51 | 51 | false | tan + sin funcs | 391 | Kindelia/HVM | 4,376 | Cuda | nicolas-abril | enricozb | Review this pull request change.
Language: Rust
File: src/ast.rs
PR Title: tan + sin funcs
BEFORE CODE: return Ok(Numb(hvm::Numb::new_sym(cast).0));
}
// Parses the symbol
let op = hvm::Numb::new_sym(match () {
// numeric operations
_ if self.try_consume("+") => hvm::OP_ADD,
_... | These symbols are trying to uniquely map to operators, so we shouldn't add sin and tan here. Notice how there's no pow, log and atan2. | 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. |
rt::collect(mem, get_var(mem, term, dynvar));
}
}
return true;
}
}
false
});
rt::Function { arity, stricts, rewriter }
}
/// Converts a Lambolt Term to a Runtime Term
fn term_to_dynterm(comp: &rb::RuleBook, term: &lang::Term, free_vars: u64) -> DynTerm {
fn c... | No issues found. | rt::collect(mem, get_var(mem, term, dynvar));
}
}
return true;
}
}
false
});
rt::Function { arity, stricts, rewriter }
}
/// Converts a Lambolt Term to a Runtime Term
fn term_to_dynterm(comp: &rb::RuleBook, term: &lang::Term, free_vars: u64) -> DynTerm {
fn c... | @@ -58,7 +58,11 @@ pub struct DynFun {
pub rules: Vec<DynRule>,
}
-pub fn build_dynfun(comp: &rb::RuleBook, rules: &[lang::Rule]) -> DynFun {
+pub fn build_dynfun(
+ dups_count: &mut DupsCount,
+ comp: &rb::RuleBook,
+ rules: &[lang::Rule],
+) -> DynFun {
let mut redex = if let lang::Term::Ctr { name: _, re... | src/builder.rs | 0 | Rust | 1 | none | 16 | 51 | 51 | true | Clean up more | 78 | Kindelia/HVM | 4,376 | Cuda | azdavis | Review this pull request change.
Language: Rust
File: src/builder.rs
PR Title: Clean up more
BEFORE CODE: rt::collect(mem, get_var(mem, term, dynvar));
}
}
return true;
}
}
false
});
rt::Function { arity, stricts, rewriter }
}
/// Converts a Lambolt Term to... | No issues found. | 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. | |
u64 done = link(mem, host, Ctr(0, func, 0));
} else {
u64 ctr0 = get_loc(arg0,0);
u64 ctr1 = alloc(mem, arit);
for (u64 i = 0; i < arit - 1; ++i) {
u64 leti = alloc(mem, 3);
link(mem, leti+2, ask_arg(mem, a... | No issues found. | u64 done = link(mem, host, Ctr(0, func, 0));
} else {
u64 ctr0 = get_loc(arg0,0);
u64 ctr1 = alloc(mem, arit);
for (u64 i = 0; i < arit - 1; ++i) {
u64 leti = alloc(mem, 3);
link(mem, leti+2, ask_arg(mem, a... | @@ -339,8 +339,8 @@ void clear(Worker* mem, u64 loc, u64 size) {
// Garbage Collection
// ------------------
-// This clears the memory used by a term that becames unreachable. It just frees
-// all its nodes recursivelly. This is called as soon as a term goes out of
+// This clears the memory used by a term that b... | src/runtime.c | 0 | C | 1 | none | 16 | 51 | 51 | true | Spelling | 113 | Kindelia/HVM | 4,376 | Cuda | jsoref | Review this pull request change.
Language: C
File: src/runtime.c
PR Title: Spelling
BEFORE CODE: u64 done = link(mem, host, Ctr(0, func, 0));
} else {
u64 ctr0 = get_loc(arg0,0);
u64 ctr1 = alloc(mem, arit);
for (u64 i = 0; i < arit - 1; ... | No issues found. | 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. | |
format!("{}/{}", env!("CARGO_MANIFEST_DIR"), sub).into()
}
fn test_file(path: &Path) {
if fs::read_to_string(path).unwrap().contains("@test-skip = 1") {
println!("skipping {path:?}");
return;
}
println!("testing {path:?}...");
let rust_output = execute_hvm(&["run".as_ref(), path.as_os_str()]).unwrap(... | No issues found. | format!("{}/{}", env!("CARGO_MANIFEST_DIR"), sub).into()
}
fn test_file(path: &Path) {
if fs::read_to_string(path).unwrap().contains("@test-skip = 1") {
println!("skipping {path:?}");
return;
}
println!("testing {path:?}...");
let rust_output = execute_hvm(&["run".as_ref(), path.as_os_str()]).unwrap(... | @@ -60,7 +60,7 @@ fn execute_hvm(args: &[&OsStr]) -> Result<String, Box<dyn Error>> {
stderr.read_to_string(&mut output)?;
Ok(if !status.success() {
- format!("exited with code {status}:\n{output}")
+ format!("{status}\n{output}")
} else {
parse_output(&output).unwrap_or_else(|err| {
panic!... | tests/run.rs | 0 | Rust | 1 | none | 16 | 51 | 51 | true | error gracefully when `@main` is missing | 346 | Kindelia/HVM | 4,376 | Cuda | tjjfvi | Review this pull request change.
Language: Rust
File: tests/run.rs
PR Title: error gracefully when `@main` is missing
BEFORE CODE: format!("{}/{}", env!("CARGO_MANIFEST_DIR"), sub).into()
}
fn test_file(path: &Path) {
if fs::read_to_string(path).unwrap().contains("@test-skip = 1") {
println!("skipping {pat... | No issues found. | 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. | |
// The Oper Interaction.
static inline bool interact_oper(Net* net, TM* tm, Port a, Port b) {
//printf("OPER %08x %08x\n", a, b);
// Allocates needed nodes and vars.
if (!get_resources(net, tm, 1, 1, 0)) {
return FALSE;
}
// Checks availability
if (node_load(net, get_val(b)) == 0) {
return FALSE;... | No issues found. |
// The Oper Interaction.
static inline bool interact_oper(Net* net, TM* tm, Port a, Port b) {
//printf("OPER %08x %08x\n", a, b);
// Allocates needed nodes and vars.
if (!get_resources(net, tm, 1, 1, 0)) {
return FALSE;
}
// Checks availability
if (node_load(net, get_val(b)) == 0) {
return FALSE;... | @@ -171,7 +171,7 @@ typedef struct Ctr {
Port args_buf[16];
} Ctr;
-// Readback: λ-Encoded Str (UTF-16)
+// Readback: λ-Encoded Str (UTF-32)
// FIXME: this is actually ASCII :|
// FIXME: remove len limit
typedef struct Str {
@@ -765,7 +765,7 @@ static inline void link(Net* net, TM* tm, Port A, Port B) {
i... | src/hvm.c | 0 | C | 1 | none | 16 | 51 | 51 | true | CUDA Basic IO | 347 | Kindelia/HVM | 4,376 | Cuda | enricozb | Review this pull request change.
Language: C
File: src/hvm.c
PR Title: CUDA Basic IO
BEFORE CODE:
// The Oper Interaction.
static inline bool interact_oper(Net* net, TM* tm, Port a, Port b) {
//printf("OPER %08x %08x\n", a, b);
// Allocates needed nodes and vars.
if (!get_resources(net, tm, 1, 1, 0)) {
... | No issues found. | 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. | |
// Loads ports.
Pair A = node_take(net, get_val(a));
Port A1 = get_fst(A);
Port A2 = get_snd(A);
Pair B = node_take(net, get_val(b));
Port B1 = get_fst(B);
Port B2 = get_snd(B);
//if (A == 0) printf("[%04x] ERROR5: %s\n", tid, show_port(a).x);
//if (B == 0) printf("[%04x] ERROR6: %s\n", tid, show_p... | No issues found. | // Loads ports.
Pair A = node_take(net, get_val(a));
Port A1 = get_fst(A);
Port A2 = get_snd(A);
Pair B = node_take(net, get_val(b));
Port B1 = get_fst(B);
Port B2 = get_snd(B);
//if (A == 0) printf("[%04x] ERROR5: %s\n", tid, show_port(a).x);
//if (B == 0) printf("[%04x] ERROR6: %s\n", tid, show_p... | @@ -21,6 +21,8 @@ typedef uint16_t u16;
typedef int32_t i32;
typedef uint32_t u32;
typedef uint64_t u64;
+typedef float f32;
+typedef double f64;
typedef _Atomic(u8) a8;
typedef _Atomic(u16) a16;
@@ -75,6 +77,10 @@ typedef u32 Numb; // Numb ::= 29-bit (rounded up to u32)
#define SWIT 0x7
// Numbers
+st... | src/hvm.c | 0 | C | 1 | none | 16 | 51 | 51 | true | Numeric Casting Operations | 361 | Kindelia/HVM | 4,376 | Cuda | enricozb | Review this pull request change.
Language: C
File: src/hvm.c
PR Title: Numeric Casting Operations
BEFORE CODE: // Loads ports.
Pair A = node_take(net, get_val(a));
Port A1 = get_fst(A);
Port A2 = get_snd(A);
Pair B = node_take(net, get_val(b));
Port B1 = get_fst(B);
Port B2 = get_snd(B);
//if (A ... | No issues found. | 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. | |
// Otherwise, just perform a normal link.
} else {
// Allocates needed nodes and vars.
if (!get_resources(net, tm, 1, 0, 0)) {
return false;
}
link_pair(net, tm, new_pair(a, b));
}
return true;
}
// Declared here for use in call interactions.
static inline bool interact_eras(Net* net, ... | No issues found. |
// Otherwise, just perform a normal link.
} else {
// Allocates needed nodes and vars.
if (!get_resources(net, tm, 1, 0, 0)) {
return false;
}
link_pair(net, tm, new_pair(a, b));
}
return true;
}
// Declared here for use in call interactions.
static inline bool interact_eras(Net* net, ... | @@ -676,6 +676,8 @@ __device__ __host__ inline Numb operate(Numb a, Numb b) {
case OP_AND: return new_f24(atan2f(av, bv));
case OP_OR: return new_f24(logf(bv) / logf(av));
case OP_XOR: return new_f24(powf(av, bv));
+ case OP_SHL: return new_f24(sin(av + bv));
+ case OP_SHR: ret... | src/hvm.cu | 0 | CUDA | 1 | none | 16 | 51 | 51 | true | tan + sin funcs | 391 | Kindelia/HVM | 4,376 | Cuda | enricozb | Review this pull request change.
Language: CUDA
File: src/hvm.cu
PR Title: tan + sin funcs
BEFORE CODE:
// Otherwise, just perform a normal link.
} else {
// Allocates needed nodes and vars.
if (!get_resources(net, tm, 1, 0, 0)) {
return false;
}
link_pair(net, tm, new_pair(a, b));
}
... | No issues found. | 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. | |
setInputText(text);
} else {
onValidityChanged("INVALID");
setInputText("");
}
};
return (
<div data-cy="task" data-task-type="create-task">
<TwoColumnsWithCards>
<>
<TaskHeader taskType={taskType} />
{task.type !== TaskType.initial_prompt && (
... | please extract to localization, also we need to check how it works on macs, we also need to hide this text on mobile. | onSubmit,
}: TaskSurveyProps<CreateTaskType, CreateTaskReply>) => {
const { t, i18n } = useTranslation(["tasks", "common"]);
const cardColor = useColorModeValue("gray.50", "gray.800");
const titleColor = useColorModeValue("gray.800", "gray.300");
const tipColor = useColorModeValue("gray.600", "gray.400");
c... | @@ -55,6 +57,7 @@ export const CreateTask = ({
{t(getTypeSafei18nKey(`tasks:${taskType.id}.instruction`))}
</Text>
)}
+ <Text color={tipColor}>Tip: Use <Kbd>ctrl</Kbd>+<Kbd>Enter</Kbd> to Review and Submit</Text> | website/src/components/Tasks/CreateTask.tsx | 26 | TypeScript | 0.429 | refactor | 117 | 44 | 51 | false | Implemented ability to press ctrl+enter (or cmd+enter) to Review/Subm… | 1,237 | LAION-AI/Open-Assistant | 29,137 | Python | AbdBarho | cooperaustinj | Review this pull request change.
Language: TypeScript
File: website/src/components/Tasks/CreateTask.tsx
PR Title: Implemented ability to press ctrl+enter (or cmd+enter) to Review/Subm…
BEFORE CODE: setInputText(text);
} else {
onValidityChanged("INVALID");
setInputText("");
}
};
retur... | please extract to localization, also we need to check how it works on macs, we also need to hide this text on mobile. | 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. |
isEditable={taskStatus.mode === "EDIT"}
isDisabled={taskStatus.mode === "SUBMITTED"}
onReplyChanged={onReplyChanged}
onValidityChanged={updateValidity}
/>
);
}
}, [taskInfo, task, taskStatus.mode, onReplyChanged, updateValidity]);
return (
<... | Why do you need to fallback to "default.continue_anyway" here? | isEditable={taskStatus.mode === "EDIT"}
isDisabled={taskStatus.mode === "SUBMITTED"}
onReplyChanged={onReplyChanged}
onValidityChanged={updateValidity}
/>
);
}
}, [taskInfo, task, taskStatus.mode, onReplyChanged, updateValidity]);
return (
<... | @@ -186,7 +186,7 @@ export const Task = () => {
show={taskStatus.mode === "DEFAULT_WARN"}
title={t(getTypeSafei18nKey(`${taskInfo.id}.unchanged_title`)) || t("default.unchanged_title")}
message={t(getTypeSafei18nKey(`${taskInfo.id}.unchanged_message`)) || t("default.unchanged_message")}
- ... | website/src/components/Tasks/Task/Task.tsx | 26 | TypeScript | 0.214 | question | 62 | 42 | 42 | false | Localize some labels that were missing in the tasks view | 1,607 | LAION-AI/Open-Assistant | 29,137 | Python | notmd | GuilleHoardings | Review this pull request change.
Language: TypeScript
File: website/src/components/Tasks/Task/Task.tsx
PR Title: Localize some labels that were missing in the tasks view
BEFORE CODE: isEditable={taskStatus.mode === "EDIT"}
isDisabled={taskStatus.mode === "SUBMITTED"}
onReplyChang... | Why do you need to fallback to "default.continue_anyway" 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. |
# (such that it will be handled by `APIClientRateLimiter`)
if not api_key or not user or not user.get("id"):
return
return await super().__call__(request, response)
class UserTaskTypeRateLimiter(RateLimiter):
"""
User-level rate limiter for a specific task type.
"""
... | To be guaranteed unique the key needs to include api-key, auth-method and user-id, beside of extracting the user from the request json it would probably be easier to get it from the oasst_user_header (`x-oasst-user`) .. which already contains auth-method+username delimited by ':'. | return
# Attempt to retrieve api_key and user information
user = (await request.json()).get("user")
# Skip when api_key and user information are not available
# (such that it will be handled by `APIClientRateLimiter`)
if not api_key or not user or not user.get("id")... | @@ -166,6 +166,50 @@ async def __call__(self, request: Request, response: Response, api_key: str = De
return await super().__call__(request, response)
+class UserTaskTypeRateLimiter(RateLimiter):
+ """
+ User-level rate limiter for a specific task type.
+ """
+
+ def __init__(
+ self,
+ ... | backend/oasst_backend/api/deps.py | 26 | Python | 0.643 | security | 281 | 51 | 51 | false | Implement separate rate limit for message submission tasks | 1,747 | LAION-AI/Open-Assistant | 29,137 | Python | andreaskoepf | olliestanley | Review this pull request change.
Language: Python
File: backend/oasst_backend/api/deps.py
PR Title: Implement separate rate limit for message submission tasks
BEFORE CODE: # (such that it will be handled by `APIClientRateLimiter`)
if not api_key or not user or not user.get("id"):
return
... | To be guaranteed unique the key needs to include api-key, auth-method and user-id, beside of extracting the user from the request json it would probably be easier to get it from the oasst_user_header (`x-oasst-user`) .. which already contains auth-method+username delimited by ':'. | 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. |
pr = self.pr
pr.ensure_user_is_enabled()
match type(interaction):
case protocol_schema.TextReplyToMessage:
logger.info(
f"Frontend reports text reply to message_id={interaction.message_id} by user={interaction.user}."
)
... | why is this no longer logged as error? | task = protocol_schema.LabelInitialPromptTask(
message_id=message.id,
prompt=message.text,
conversation=prepare_conversation([message]),
valid_labels=list(map(lambda x: x.value, valid_labels)),
mandatory_... | @@ -693,36 +695,51 @@ async def handle_interaction(self, interaction: protocol_schema.AnyInteraction)
if not settings.DEBUG_SKIP_EMBEDDING_COMPUTATION:
try:
- hugging_face_api = HuggingFaceAPI(
- f"{HfUrl.HUGGINGFACE_FEATURE_EXTRA... | backend/oasst_backend/tree_manager.py | 26 | Python | 0.214 | question | 38 | 51 | 51 | false | feature: Using Celery for APIs and periodic tasks | 1,754 | LAION-AI/Open-Assistant | 29,137 | Python | andreaskoepf | melvinebenezer | Review this pull request change.
Language: Python
File: backend/oasst_backend/tree_manager.py
PR Title: feature: Using Celery for APIs and periodic tasks
BEFORE CODE: pr = self.pr
pr.ensure_user_is_enabled()
match type(interaction):
case protocol_schema.TextReplyToMessage:
... | why is this no longer logged as error? | 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.on_event("startup")
@repeat_every(seconds=60 * settings.USER_STATS_INTERVAL_MONTH, wait_first=False)
@managed_tx_function(auto_commit=CommitMode.COMMIT)
def update_leader_board_month(session: Session) -> None:
try:
usr = UserStatsRepository(session)
usr.update_stats(time_frame=UserStatsTimeFra... | why is update_user_streak() now still part of main? | @app.on_event("startup")
@repeat_every(seconds=60 * settings.USER_STATS_INTERVAL_MONTH, wait_first=False)
@managed_tx_function(auto_commit=CommitMode.COMMIT)
def update_leader_board_month(session: Session) -> None:
try:
usr = UserStatsRepository(session)
usr.update_stats(time_frame=UserStatsTimeFram... | @@ -284,44 +288,46 @@ def update_leader_board_total(session: Session) -> None:
@app.on_event("startup")
-@repeat_every(seconds=60 * 60 * settings.USER_STREAK_UPDATE_INTERVAL, wait_first=False)
-def update_user_streak(session: Session) -> None:
+@repeat_every(seconds=3600, wait_first=False)
+def update_user_streak(... | backend/main.py | 26 | Python | 0.286 | question | 52 | 51 | 51 | false | feature: Using Celery for APIs and periodic tasks | 1,754 | LAION-AI/Open-Assistant | 29,137 | Python | andreaskoepf | melvinebenezer | Review this pull request change.
Language: Python
File: backend/main.py
PR Title: feature: Using Celery for APIs and periodic tasks
BEFORE CODE:
@app.on_event("startup")
@repeat_every(seconds=60 * settings.USER_STATS_INTERVAL_MONTH, wait_first=False)
@managed_tx_function(auto_commit=CommitMode.COMMIT)
def update_l... | why is update_user_streak() now still part of main? | 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. |
message = pr.store_text_reply(
text=interaction.text,
lang=interaction.lang,
frontend_message_id=interaction.message_id,
user_frontend_message_id=interaction.user_message_id,
)
if not message... | will these comments be removed? | )
parent_message_id = message.id
message_tree_id = message.message_tree_id
case TaskType.PROMPT:
logger.info("Generating an InitialPromptTask.")
task = protocol_schema.InitialPromptTask(hint=None)
case _:
... | @@ -693,36 +695,51 @@ async def handle_interaction(self, interaction: protocol_schema.AnyInteraction)
if not settings.DEBUG_SKIP_EMBEDDING_COMPUTATION:
try:
- hugging_face_api = HuggingFaceAPI(
- f"{HfUrl.HUGGINGFACE_FEATURE_EXTRA... | backend/oasst_backend/tree_manager.py | 26 | Python | 0.143 | question | 31 | 51 | 51 | false | feature: Using Celery for APIs and periodic tasks | 1,754 | LAION-AI/Open-Assistant | 29,137 | Python | andreaskoepf | melvinebenezer | Review this pull request change.
Language: Python
File: backend/oasst_backend/tree_manager.py
PR Title: feature: Using Celery for APIs and periodic tasks
BEFORE CODE: message = pr.store_text_reply(
text=interaction.text,
lang=interaction.lang,
... | will these comments be 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. |
`/api/leaderboard?time_frame=${timeFrame}&limit=${limit}&includeUserStats=${!hideCurrentUserRanking}`
);
const isAdminOrMod = useHasAnyRole(["admin", "moderator"]);
const columns: DataTableColumnDef<WindowLeaderboardEntity>[] = useMemo(
() => [
{
...columnHelper.accessor("rank", {
... | is it possible to only ternary on the url? | } = useFetchBoard<LeaderboardReply & { user_stats_window?: LeaderboardReply["leaderboard"] }>(
`/api/leaderboard?time_frame=${timeFrame}&limit=${limit}&includeUserStats=${!hideCurrentUserRanking}`
);
const isAdminOrMod = useHasAnyRole(["admin", "moderator"]);
const columns: DataTableColumnDef<WindowLeader... | @@ -61,14 +62,34 @@ export const LeaderboardTable = ({
},
columnHelper.accessor("display_name", {
header: t("user"),
- cell: ({ getValue, row }) =>
- isAdminOrMod ? (
- <Link as={NextLink} href={`/admin/manage_user/${row.original.user_id}`}>
- {getValue()}
... | website/src/components/LeaderboardTable/LeaderboardTable.tsx | 26 | TypeScript | 0.071 | question | 42 | 51 | 51 | false | Display user avatar in leaderboard | 1,767 | LAION-AI/Open-Assistant | 29,137 | Python | AbdBarho | mrloldev | Review this pull request change.
Language: TypeScript
File: website/src/components/LeaderboardTable/LeaderboardTable.tsx
PR Title: Display user avatar in leaderboard
BEFORE CODE: `/api/leaderboard?time_frame=${timeFrame}&limit=${limit}&includeUserStats=${!hideCurrentUserRanking}`
);
const isAdminOrMod = u... | is it possible to only ternary on the url? | 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. |
cell: (ctx) =>
ctx.row.original.isSpaceRow ? (
<SpaceRow></SpaceRow>
) : isAdminOrMod ? (
jsonExpandRowModel.renderCell(ctx)
) : (
ctx.getValue()
),
}),
span: (cell) => (cell.row.original.isSpaceRow ? 6 :... | I noticed that you are calling `getValue` more than once, maybe should we cache it? I realise this prevents the explicit return. Additionally, might it make sense to create a component for this i.e `<UserAvatar displayName={displayname} />` incase we want to use it again? | header: t("rank"),
cell: (ctx) =>
ctx.row.original.isSpaceRow ? (
<SpaceRow></SpaceRow>
) : isAdminOrMod ? (
jsonExpandRowModel.renderCell(ctx)
) : (
ctx.getValue()
),
}),
span: (cell) => (cell.... | @@ -61,14 +62,34 @@ export const LeaderboardTable = ({
},
columnHelper.accessor("display_name", {
header: t("user"),
- cell: ({ getValue, row }) =>
- isAdminOrMod ? (
- <Link as={NextLink} href={`/admin/manage_user/${row.original.user_id}`}>
- {getValue()}
... | website/src/components/LeaderboardTable/LeaderboardTable.tsx | 26 | TypeScript | 0.643 | performance | 274 | 51 | 51 | false | Display user avatar in leaderboard | 1,767 | LAION-AI/Open-Assistant | 29,137 | Python | rjmacarthy | mrloldev | Review this pull request change.
Language: TypeScript
File: website/src/components/LeaderboardTable/LeaderboardTable.tsx
PR Title: Display user avatar in leaderboard
BEFORE CODE: cell: (ctx) =>
ctx.row.original.isSpaceRow ? (
<SpaceRow></SpaceRow>
) : isAdminOrMod ? ... | I noticed that you are calling `getValue` more than once, maybe should we cache it? I realise this prevents the explicit return. Additionally, might it make sense to create a component for this i.e `<UserAvatar displayName={displayname} />` incase we want to use it 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. |
<>
<Box minH={330}>
<Bar options={barOptions} data={barData} />
</Box>
</>
);
};
// Returns the color for the bar chart. If the stat is a message tree state, it returns
// an array of colors depending on the state. Otherwise, it returns an empty string, so
// that the default color is use... | You dont need to reassign the `data` variable. `sort` mutate the original array | return (
<>
<Box minH={330}>
<Bar options={barOptions} data={barData} />
</Box>
</>
);
};
// Returns the color for the bar chart. If the stat is a message tree state, it returns
// an array of colors depending on the state. Otherwise, it returns an empty string, so
// that the default c... | @@ -249,10 +267,30 @@ export const MessageTreeStateStatsStacked = ({ stat }: MessageTreeStateStatsProp
);
};
+// Returns the color for the bar chart. If the stat is a message tree state, it returns
+// an array of colors depending on the state. Otherwise, it returns an empty string, so
+// that the default color ... | website/src/components/Stats/Stats.components.tsx | 26 | TypeScript | 0.357 | style | 79 | 51 | 51 | false | Make the colors of the "Message tree states" match | 1,829 | LAION-AI/Open-Assistant | 29,137 | Python | notmd | GuilleHoardings | Review this pull request change.
Language: TypeScript
File: website/src/components/Stats/Stats.components.tsx
PR Title: Make the colors of the "Message tree states" match
BEFORE CODE: <>
<Box minH={330}>
<Bar options={barOptions} data={barData} />
</Box>
</>
);
};
// Returns the colo... | You dont need to reassign the `data` variable. `sort` mutate the original array | 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. |
columnHelper.accessor("aborted_low_grade", {
cell: (info) => info.getValue(),
header: t("aborted_low_grade"),
meta: {
isNumeric: true,
},
}),
columnHelper.accessor("halted_by_moderator", {
cell: (info) => info.getValue(),
header: t("halted_by_moderator"),
me... | same here, just chain the `sort` | columnHelper.accessor("aborted_low_grade", {
cell: (info) => info.getValue(),
header: t("aborted_low_grade"),
meta: {
isNumeric: true,
},
}),
columnHelper.accessor("halted_by_moderator", {
cell: (info) => info.getValue(),
header: t("halted_by_moderator"),
me... | @@ -173,6 +184,11 @@ export const MessageTreeStateStats = ({ stat, titleFn }: MessageTreeStateStatsPr
const uniqueLangs = Array.from(new Set(stat.stats.map((s) => s.lang)));
const [selectedLang, setSelectedLang] = useState("en");
const stats = stat.stats.filter((item) => item.lang === selectedLang);
+ const s... | website/src/components/Stats/Stats.components.tsx | 26 | TypeScript | 0.214 | style | 32 | 51 | 51 | false | Make the colors of the "Message tree states" match | 1,829 | LAION-AI/Open-Assistant | 29,137 | Python | notmd | GuilleHoardings | Review this pull request change.
Language: TypeScript
File: website/src/components/Stats/Stats.components.tsx
PR Title: Make the colors of the "Message tree states" match
BEFORE CODE: columnHelper.accessor("aborted_low_grade", {
cell: (info) => info.getValue(),
header: t("aborted_low_grade"),
... | same here, just chain the `sort` | 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 MessageTreeStateStatsProps = {
titleFn?: (name: string) => string;
stat: StatType & {
stats: MessageTreesStatesByLang;
};
};
// The headers come from the message tree State. These two states are not
// considered because they make the table too wide and they are not so
// interesting:
// - "ready_fo... | could you rename to something like `STATE_COLORS`? since this is a constant. | };
type MessageTreeStateStatsProps = {
titleFn?: (name: string) => string;
stat: StatType & {
stats: MessageTreesStatesByLang;
};
};
// The headers come from the message tree State. These two states are not
// considered because they make the table too wide and they are not so
// interesting:
// - "ready_fo... | @@ -53,6 +53,17 @@ const interestingStates = [
"halted_by_moderator",
];
+const stateColors = { | website/src/components/Stats/Stats.components.tsx | 26 | TypeScript | 0.429 | question | 76 | 51 | 51 | false | Make the colors of the "Message tree states" match | 1,829 | LAION-AI/Open-Assistant | 29,137 | Python | AbdBarho | GuilleHoardings | Review this pull request change.
Language: TypeScript
File: website/src/components/Stats/Stats.components.tsx
PR Title: Make the colors of the "Message tree states" match
BEFORE CODE: };
type MessageTreeStateStatsProps = {
titleFn?: (name: string) => string;
stat: StatType & {
stats: MessageTreesStatesByL... | could you rename to something like `STATE_COLORS`? since this is a constant. | 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 { t } = useTranslation();
return (
<Card>
{isLoading && <Progress size="sm" isIndeterminate />}
<Flex p="6" gap="4" direction={["column", "row"]}>
<TaskInfo id={task.id} output={t("submit_your_answer")} />
<Flex width={["full", "fit-content"]} justify="center" ml="auto" gap={2... | Can you update the aria-label too? | const { t } = useTranslation();
return (
<Card>
{isLoading && <Progress size="sm" isIndeterminate />}
<Flex p="6" gap="4" direction={["column", "row"]}>
<TaskInfo id={task.id} output={t("submit_your_answer")} />
<Flex width={["full", "fit-content"]} justify="center" ml="auto" gap={2... | @@ -53,7 +53,7 @@ export const TaskControls = ({
</>
) : (
<>
- <Tooltip label="Edit">
+ <Tooltip label={t("edit")}>
<IconButton size="lg" data-cy="edit" aria-label="edit" onClick={onEdit} icon={<Edit2 size="1em" />} /> | website/src/components/Survey/TaskControls.tsx | 26 | TypeScript | 0.071 | question | 34 | 44 | 50 | false | 404 [en, ru], edit [en, ru], keeping upd, fixes | 1,842 | LAION-AI/Open-Assistant | 29,137 | Python | notmd | echo0x22 | Review this pull request change.
Language: TypeScript
File: website/src/components/Survey/TaskControls.tsx
PR Title: 404 [en, ru], edit [en, ru], keeping upd, fixes
BEFORE CODE: const { t } = useTranslation();
return (
<Card>
{isLoading && <Progress size="sm" isIndeterminate />}
<Flex p="6" gap... | Can you update the aria-label 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. |
import { CopyIcon, CheckIcon } from "@chakra-ui/icons";
import {
Box,
Button,
Modal,
ModalBody,
ModalCloseButton,
ModalContent,
ModalFooter,
ModalHeader,
ModalOverlay,
SystemStyleObject,
useDisclosure,
useToast,
} from "@chakra-ui/react";
import { Prose } from "@nikolovlazar/chakra-ui-prose";
im... | Can you update to use https://lucide.dev/ icon? and remove the `@charka-ui/icons` deps | import {
Box,
Button,
Modal,
ModalBody,
ModalCloseButton,
ModalContent,
ModalFooter,
ModalHeader,
ModalOverlay,
SystemStyleObject,
useDisclosure,
} from "@chakra-ui/react";
import { Prose } from "@nikolovlazar/chakra-ui-prose";
import NextLink from "next/link";
import { useTranslation } from "next... | @@ -1,3 +1,4 @@
+import { CopyIcon, CheckIcon } from "@chakra-ui/icons"; | website/src/components/Messages/RenderedMarkdown.tsx | 1 | TypeScript | 0.429 | suggestion | 86 | 26 | 26 | false | Add button to copy code in markdown | 1,845 | LAION-AI/Open-Assistant | 29,137 | Python | notmd | Slowlife01 | Review this pull request change.
Language: TypeScript
File: website/src/components/Messages/RenderedMarkdown.tsx
PR Title: Add button to copy code in markdown
BEFORE CODE: import { CopyIcon, CheckIcon } from "@chakra-ui/icons";
import {
Box,
Button,
Modal,
ModalBody,
ModalCloseButton,
ModalContent,
Mo... | Can you update to use https://lucide.dev/ icon? and remove the `@charka-ui/icons` deps | 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. |
borderBottomColor: "gray.400",
_dark: {
borderBottomColor: "gray.700",
},
},
"table thead tr": {
borderBottomColor: "gray.400",
borderBottomWidth: "1px",
_dark: {
borderBottomColor: "gray.700",
},
},
"ol li::marker": {
content: "counter(list-item) '.'",
},
};
const... | This will cause a markdown containing multiple `code` blocks will show a copied state at the same time. You better extract the `code` to a separate component | borderInlineStartColor: "gray.500",
},
},
"table tbody tr": {
borderBottomColor: "gray.400",
_dark: {
borderBottomColor: "gray.700",
},
},
"table thead tr": {
borderBottomColor: "gray.400",
borderBottomWidth: "1px",
_dark: {
borderBottomColor: "gray.700",
},
}... | @@ -83,17 +86,64 @@ const disallowedElements = ["img"];
const RenderedMarkdown = ({ markdown }: RenderedMarkdownProps) => {
const { isOpen, onOpen, onClose } = useDisclosure();
const [link, setLink] = useState<string | undefined>();
+ const [isCopied, setIsCopied] = useState(false); | website/src/components/Messages/RenderedMarkdown.tsx | 26 | TypeScript | 0.571 | refactor | 157 | 51 | 51 | false | Add button to copy code in markdown | 1,845 | LAION-AI/Open-Assistant | 29,137 | Python | notmd | Slowlife01 | Review this pull request change.
Language: TypeScript
File: website/src/components/Messages/RenderedMarkdown.tsx
PR Title: Add button to copy code in markdown
BEFORE CODE: borderBottomColor: "gray.400",
_dark: {
borderBottomColor: "gray.700",
},
},
"table thead tr": {
borderBottomColor: "g... | This will cause a markdown containing multiple `code` blocks will show a copied state at the same time. You better extract the `code` to a separate 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. |
import { Prose } from "@nikolovlazar/chakra-ui-prose";
import NextLink from "next/link";
import { useTranslation } from "next-i18next";
import { memo, MouseEvent, useMemo, useState } from "react";
import ReactMarkdown from "react-markdown";
import type { ReactMarkdownOptions } from "react-markdown/lib/react-markdown";
... | Also why you need marginRight here? | import { useTranslation } from "next-i18next";
import { memo, MouseEvent, useMemo, useState } from "react";
import ReactMarkdown from "react-markdown";
import type { ReactMarkdownOptions } from "react-markdown/lib/react-markdown";
import remarkGfm from "remark-gfm";
import { RenderedCodeblock } from "src/components/Mes... | @@ -36,6 +38,7 @@ const sx: SystemStyleObject = {
bg: "gray.300",
p: 0.5,
borderRadius: "2px",
+ marginRight: "40px", | website/src/components/Messages/RenderedMarkdown.tsx | 26 | TypeScript | 0.071 | question | 35 | 51 | 51 | false | Add button to copy code in markdown | 1,845 | LAION-AI/Open-Assistant | 29,137 | Python | notmd | Slowlife01 | Review this pull request change.
Language: TypeScript
File: website/src/components/Messages/RenderedMarkdown.tsx
PR Title: Add button to copy code in markdown
BEFORE CODE: import { Prose } from "@nikolovlazar/chakra-ui-prose";
import NextLink from "next/link";
import { useTranslation } from "next-i18next";
import {... | Also why you need marginRight 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. |
if num_red_flag is not None and num_red_flag >= self.cfg.auto_mod_red_flags:
if m.parent_id is None:
logger.warning(
f"[AUTO MOD] Halting tree {m.message_tree_id}, initial prompt got too many red flags ({m.emojis})."
)
... | Could you move this to the [TreeManagerConfiguration](https://github.com/LAION-AI/Open-Assistant/blob/main/backend/oasst_backend/config.py)? The setting then still can be set via env-variable and this setting would be handled in the same way all other TreeManager settings are handled. |
if num_red_flag is not None and num_red_flag >= self.cfg.auto_mod_red_flags:
if m.parent_id is None:
logger.warning(
f"[AUTO MOD] Halting tree {m.message_tree_id}, initial prompt got too many red flags ({m.emojis})."
)
... | @@ -366,8 +367,14 @@ def determine_task_availability(self, lang: str) -> dict[protocol_schema.TaskReq
lang = "en"
logger.warning("Task availability request without lang tag received, assuming lang='en'.")
+ init_prompt_disabled_langs = os.getenv("INIT_PROMPT_DISABLED_LANGS", "none") | backend/oasst_backend/tree_manager.py | 26 | Python | 0.643 | refactor | 285 | 51 | 51 | false | Disable Initial Prompt Task for en and es Locales | 1,849 | LAION-AI/Open-Assistant | 29,137 | Python | andreaskoepf | hzj5790 | Review this pull request change.
Language: Python
File: backend/oasst_backend/tree_manager.py
PR Title: Disable Initial Prompt Task for en and es Locales
BEFORE CODE:
if num_red_flag is not None and num_red_flag >= self.cfg.auto_mod_red_flags:
if m.parent_id is None:
... | Could you move this to the [TreeManagerConfiguration](https://github.com/LAION-AI/Open-Assistant/blob/main/backend/oasst_backend/config.py)? The setting then still can be set via env-variable and this setting would be handled in the same way all other TreeManager settings are handled. | 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. |
mandatory_labels_assistant_reply: Optional[list[TextLabel]] = [TextLabel.spam]
"""Mandatory labels in text-labeling tasks for assistant replies."""
mandatory_labels_prompter_reply: Optional[list[TextLabel]] = [TextLabel.spam]
"""Mandatory labels in text-labeling tasks for prompter replies."""
rank... | It should be possible to set up a fresh OA server for separate data collection projects. Initial prompts should not be disabled by default. | mandatory_labels_assistant_reply: Optional[list[TextLabel]] = [TextLabel.spam]
"""Mandatory labels in text-labeling tasks for assistant replies."""
mandatory_labels_prompter_reply: Optional[list[TextLabel]] = [TextLabel.spam]
"""Mandatory labels in text-labeling tasks for prompter replies."""
rank... | @@ -149,6 +149,8 @@ class TreeManagerConfiguration(BaseModel):
"""Maximum number of prompts in prompt_lottery_waiting state per language. If this value
is exceeded no new initial prompt tasks for that language are generated."""
+ init_prompt_disabled_langs: list = ["en", "es"] | backend/oasst_backend/config.py | 26 | Python | 0.429 | suggestion | 140 | 51 | 51 | false | Disable Initial Prompt Task for en and es Locales | 1,849 | LAION-AI/Open-Assistant | 29,137 | Python | andreaskoepf | hzj5790 | Review this pull request change.
Language: Python
File: backend/oasst_backend/config.py
PR Title: Disable Initial Prompt Task for en and es Locales
BEFORE CODE: mandatory_labels_assistant_reply: Optional[list[TextLabel]] = [TextLabel.spam]
"""Mandatory labels in text-labeling tasks for assistant replies."""... | It should be possible to set up a fresh OA server for separate data collection projects. Initial prompts should not be disabled by default. | 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. |
</HStack>
),
}),
];
// TODO move this to somewhere
const DateDiff = ({ children }: { children: string | Date | number }) => {
const date = new Date(children);
const diff = formatDistanceToNow(date, { addSuffix: true });
return (
<Tooltip label={formatISO9075(date)} placement="top">
{diff}
... | You should not ignore eslint here. Please add the deps to 2nd arg | sx={{
":disabled": {
opacity: 1,
},
}}
/>
);
})}
</Flex>
);
},
}),
columnHelper.accessor("created_date", {... | @@ -106,5 +119,17 @@ const DateDiff = ({ children }: { children: string | Date | number }) => {
};
export const AdminMessageTable = (props: StrictOmit<DataTableProps<Message>, "columns">) => {
+ const { trigger: deleteMessage } = useSWRMutation("/api/admin/user_messages", (path, args: { arg: string }) =>
+ del(... | website/src/components/Messages/AdminMessageTable.tsx | 26 | TypeScript | 0.286 | style | 65 | 31 | 51 | false | Add ability to Delete Messages From the List View in User Detail View… | 1,860 | LAION-AI/Open-Assistant | 29,137 | Python | notmd | johnflux | Review this pull request change.
Language: TypeScript
File: website/src/components/Messages/AdminMessageTable.tsx
PR Title: Add ability to Delete Messages From the List View in User Detail View…
BEFORE CODE: </HStack>
),
}),
];
// TODO move this to somewhere
const DateDiff = ({ children }: { children: s... | You should not ignore eslint here. Please add the deps to 2nd arg | 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. |
<DataTableAction
as={NextLink}
href={ROUTES.ADMIN_MESSAGE_DETAIL(getValue())}
icon={Eye}
aria-label="View message"
/>
{!row.original.deleted && (
<DataTableAction onClick={() => handleDeleteMessage(getValue())} icon={Trash} aria-label="Delete mes... | Why you change the swr key here? | .sort(([emoji]) => -emoji)
.map(([emoji, count]) => {
return (
<MessageEmojiButton
key={emoji}
emoji={{ name: emoji, count }}
checked={row.original.user_emojis.includes(emoji)}
... | @@ -106,5 +119,17 @@ const DateDiff = ({ children }: { children: string | Date | number }) => {
};
export const AdminMessageTable = (props: StrictOmit<DataTableProps<Message>, "columns">) => {
+ const { trigger: deleteMessage } = useSWRMutation("/api/admin/user_messages", (path, args: { arg: string }) => | website/src/components/Messages/AdminMessageTable.tsx | 26 | TypeScript | 0.143 | question | 32 | 40 | 51 | false | Add ability to Delete Messages From the List View in User Detail View… | 1,860 | LAION-AI/Open-Assistant | 29,137 | Python | notmd | johnflux | Review this pull request change.
Language: TypeScript
File: website/src/components/Messages/AdminMessageTable.tsx
PR Title: Add ability to Delete Messages From the List View in User Detail View…
BEFORE CODE: <DataTableAction
as={NextLink}
href={ROUTES.ADMIN_MESSAGE_DETAIL(getValue())}
... | Why you change the swr key 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. |
onLabel: () => void;
onReport: () => void;
message: Message;
}) => {
const toast = useToast();
const { t } = useTranslation(["message", "common"]);
const { id } = message;
const { trigger: deleteMessage } = useSWRMutation(`/api/admin/messages`, () =>
del(`/api/admin/delete_message/${id}`)
);
cons... | You need to call mutate to revalidate the data here. The key should be something like this `/api/messages/${id}/tree` | userEmoji: string[];
onLabel: () => void;
onReport: () => void;
message: Message;
}) => {
const toast = useToast();
const { t } = useTranslation(["message", "common"]);
const { id } = message;
const { trigger: stopTree } = useSWRMutation(`/api/admin/stop_tree/${id}`, put, {
onSuccess: () => {
... | @@ -249,7 +250,6 @@ const MessageActions = ({
const handleDelete = async () => {
await deleteMessage();
- mutate((key) => typeof key === "string" && key.startsWith("/api/messages"), undefined, { revalidate: true }); | website/src/components/Messages/MessageTableEntry.tsx | 26 | TypeScript | 0.571 | suggestion | 117 | 51 | 51 | false | Add ability to Delete Messages From the List View in User Detail View… | 1,860 | LAION-AI/Open-Assistant | 29,137 | Python | notmd | johnflux | Review this pull request change.
Language: TypeScript
File: website/src/components/Messages/MessageTableEntry.tsx
PR Title: Add ability to Delete Messages From the List View in User Detail View…
BEFORE CODE: onLabel: () => void;
onReport: () => void;
message: Message;
}) => {
const toast = useToast();
con... | You need to call mutate to revalidate the data here. The key should be something like this `/api/messages/${id}/tree` | 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 LIMIT = 10;
const handler = withoutRole("banned", async (req, res, token) => {
const user = await getBackendUserCore(token.sub);
const clien... | There is no use case for this, can you remove it? | import { withoutRole } from "src/lib/auth";
import { createApiClientFromUser } from "src/lib/oasst_client_factory";
import { getBackendUserCore } from "src/lib/users";
const LIMIT = 10;
const handler = withoutRole("banned", async (req, res, token) => {
const user = await getBackendUserCore(token.sub);
const clien... | @@ -2,10 +2,25 @@ import { withoutRole } from "src/lib/auth";
import { createApiClientFromUser } from "src/lib/oasst_client_factory";
import { getBackendUserCore } from "src/lib/users";
+const LIMIT = 10;
+
const handler = withoutRole("banned", async (req, res, token) => {
const user = await getBackendUserCore(... | website/src/pages/api/messages/user.ts | 22 | TypeScript | 0.143 | question | 49 | 28 | 23 | false | Show all my messages | 1,864 | LAION-AI/Open-Assistant | 29,137 | Python | notmd | johnflux | Review this pull request change.
Language: TypeScript
File: website/src/pages/api/messages/user.ts
PR Title: Show all my messages
BEFORE CODE: import { withoutRole } from "src/lib/auth";
import { createApiClientFromUser } from "src/lib/oasst_client_factory";
import { getBackendUserCore } from "src/lib/users";
cons... | There is no use case for this, can you remove 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. |
import { withoutRole } from "src/lib/auth";
import { createApiClientFromUser } from "src/lib/oasst_client_factory";
import { getBackendUserCore } from "src/lib/users";
const LIMIT = 10;
const handler = withoutRole("banned", async (req, res, token) => {
const user = await getBackendUserCore(token.sub);
const clien... | I believe we should not expose this until #1884 has been discussed | import { withoutRole } from "src/lib/auth";
import { createApiClientFromUser } from "src/lib/oasst_client_factory";
import { getBackendUserCore } from "src/lib/users";
const LIMIT = 10;
const handler = withoutRole("banned", async (req, res, token) => {
const user = await getBackendUserCore(token.sub);
const clien... | @@ -2,10 +2,25 @@ import { withoutRole } from "src/lib/auth";
import { createApiClientFromUser } from "src/lib/oasst_client_factory";
import { getBackendUserCore } from "src/lib/users";
+const LIMIT = 10;
+
const handler = withoutRole("banned", async (req, res, token) => {
const user = await getBackendUserCore(... | website/src/pages/api/messages/user.ts | 15 | TypeScript | 0.286 | suggestion | 66 | 28 | 23 | false | Show all my messages | 1,864 | LAION-AI/Open-Assistant | 29,137 | Python | notmd | johnflux | Review this pull request change.
Language: TypeScript
File: website/src/pages/api/messages/user.ts
PR Title: Show all my messages
BEFORE CODE: import { withoutRole } from "src/lib/auth";
import { createApiClientFromUser } from "src/lib/oasst_client_factory";
import { getBackendUserCore } from "src/lib/users";
cons... | I believe we should not expose this until #1884 has been discussed | 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 sqlmodel
from loguru import logger
from oasst_inference_server import models
from oasst_shared.schemas import inference
class UserChatRepository:
def __init__(self, session: sqlmodel.Session, user_id: str | None, do_commit=True) -> None:
self.session = session
self.user_id = ... | What's the rationale for making this a `BaseModel` here? Should we not have this be consistent with `ChatRepository` and either have both or neither as `BaseModel`s? | import fastapi
import pydantic
import sqlmodel
from loguru import logger
from oasst_inference_server import models
from oasst_shared.schemas import inference
class UserChatRepository(pydantic.BaseModel):
session: sqlmodel.Session
user_id: str = pydantic.Field(..., min_length=1)
do_commit: bool = True
... | @@ -1,33 +1,34 @@
import fastapi
+import pydantic
import sqlmodel
from loguru import logger
from oasst_inference_server import models
from oasst_shared.schemas import inference
-class UserChatRepository:
- def __init__(self, session: sqlmodel.Session, user_id: str | None, do_commit=True) -> None:
- s... | inference/server/oasst_inference_server/user_chat_repository.py | 9 | Python | 0.571 | question | 165 | 34 | 34 | false | Various fixes in inference | 1,865 | LAION-AI/Open-Assistant | 29,137 | Python | olliestanley | yk | Review this pull request change.
Language: Python
File: inference/server/oasst_inference_server/user_chat_repository.py
PR Title: Various fixes in inference
BEFORE CODE: import fastapi
import sqlmodel
from loguru import logger
from oasst_inference_server import models
from oasst_shared.schemas import inference
cl... | What's the rationale for making this a `BaseModel` here? Should we not have this be consistent with `ChatRepository` and either have both or neither as `BaseModel`s? | 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.set_defaults(deepspeed=False)
if notebook:
args, remaining = parser.parse_known_args(notebook_args)
else:
args, remaining = parser.parse_known_args()
print(args)
# Config from YAML
conf = {}
configs = read_yamls("./configs")
for name in args.configs:
if ... | Should it fail if not set or could we use `int(os.getenv("WORLD_SIZE", default="1"))`? |
if notebook:
args, remaining = parser.parse_known_args(notebook_args)
else:
args, remaining = parser.parse_known_args()
print(args)
# Config from YAML
conf = {}
configs = read_yamls("./configs")
for name in args.configs:
if "," in name:
for n in name.sp... | @@ -186,6 +188,12 @@ def argument_parsing(notebook=False, notebook_args=None):
conf["local_rank"] = args.local_rank
conf["deepspeed"] = args.deepspeed
+ # get the world size in deeepspeed
+ if conf["deepspeed"]:
+ conf["world_size"] = int(os.environ["WORLD_SIZE"]) | model/model_training/trainer_sft.py | 26 | Python | 0.429 | bug | 86 | 51 | 51 | false | Distributed Sampler | 1,869 | LAION-AI/Open-Assistant | 29,137 | Python | andreaskoepf | sanagno | Review this pull request change.
Language: Python
File: model/model_training/trainer_sft.py
PR Title: Distributed Sampler
BEFORE CODE: parser.set_defaults(deepspeed=False)
if notebook:
args, remaining = parser.parse_known_args(notebook_args)
else:
args, remaining = parser.parse_known_ar... | Should it fail if not set or could we use `int(os.getenv("WORLD_SIZE", default="1"))`? | 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 (idx === -1) {
newValues = [...filterValues, value];
} else {
newValues = filterValues.map((oldValue) => (oldValue.id === value.id ? value : oldValue));
}
onFilterChange && onFilterChange(newValues);
};
return (
<>
{!disablePagination && (
<Flex mb="2">
<Bu... | is it possible to define the whitespace on the element directly? not `sx`? | if (idx === -1) {
newValues = [...filterValues, value];
} else {
newValues = filterValues.map((oldValue) => (oldValue.id === value.id ? value : oldValue));
}
onFilterChange && onFilterChange(newValues);
};
return (
<>
{!disablePagination && (
<Flex mb="2">
<Bu... | @@ -124,7 +124,7 @@ export const DataTable = <T,>({
<TableCaption pb={0}>{caption}</TableCaption>
<Thead>
{getHeaderGroups().map((headerGroup) => (
- <Tr key={headerGroup.id} sx={{ "white-space": "normal" }}>
+ <Tr key={headerGroup.id} sx={{ whiteSpace: "norm... | website/src/components/DataTable/DataTable.tsx | 26 | TypeScript | 0.357 | question | 74 | 51 | 51 | false | Scroll to message when loaded | 1,886 | LAION-AI/Open-Assistant | 29,137 | Python | AbdBarho | johnflux | Review this pull request change.
Language: TypeScript
File: website/src/components/DataTable/DataTable.tsx
PR Title: Scroll to message when loaded
BEFORE CODE: if (idx === -1) {
newValues = [...filterValues, value];
} else {
newValues = filterValues.map((oldValue) => (oldValue.id === value.id ? ... | is it possible to define the whitespace on the element directly? not `sx`? | 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 handleOnClick = useCallback(() => {
enabled && router.push(ROUTES.MESSAGE_DETAIL(message.id));
}, [enabled, message.id, router]);
return (
<HStack w={["full", "full", "full", "fit-content"]} gap={0.5} alignItems="start" maxW="full" position="relative">
{!inlineAvatar && avatar}
<Box
... | have you tried with `autoFocus` on the target element? does it solve the problem? | };
const isAdminOrMod = useHasAnyRole(["admin", "moderator"]);
const { t } = useTranslation(["message"]);
const router = useRouter();
const highlightedElementRef = useRef();
useScrollToElementOnMount(scrollToHighlighted ? highlightedElementRef : undefined);
const handleOnClick = useCallback(() => {
... | @@ -124,6 +126,7 @@ export function MessageTableEntry({ message, enabled, highlight, showAuthorBadge
outline={highlight ? "2px solid black" : undefined}
outlineColor={highlightColor}
cursor={enabled ? "pointer" : undefined}
+ ref={highlight ? focusElementRef : undefined}
overf... | website/src/components/Messages/MessageTableEntry.tsx | 26 | TypeScript | 0.357 | question | 81 | 51 | 51 | false | Scroll to message when loaded | 1,886 | LAION-AI/Open-Assistant | 29,137 | Python | AbdBarho | johnflux | Review this pull request change.
Language: TypeScript
File: website/src/components/Messages/MessageTableEntry.tsx
PR Title: Scroll to message when loaded
BEFORE CODE: const handleOnClick = useCallback(() => {
enabled && router.push(ROUTES.MESSAGE_DETAIL(message.id));
}, [enabled, message.id, router]);
re... | have you tried with `autoFocus` on the target element? does it solve 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. |
mt={inlineAvatar ? 0 : `6px`}
mb={inlineAvatar ? 1.5 : 0}
name={`${boolean(message.is_assistant) ? "Assistant" : "User"}`}
src={`${boolean(message.is_assistant) ? "/images/logos/logo.png" : "/images/temp-avatars/av1.jpg"}`}
/>
),
[borderColor, inlineAvatar, message.is_assis... | We only want to scroll on /messages/[id] and /admin/messages/[id] pages. Can you add another prop `scrollToHightlighted` or something similar? It should be false by default. |
const avatar = useMemo(
() => (
<Avatar
borderColor={borderColor}
size={inlineAvatar ? "xs" : "sm"}
mr={inlineAvatar ? 2 : 0}
mt={inlineAvatar ? 0 : `6px`}
mb={inlineAvatar ? 1.5 : 0}
name={`${boolean(message.is_assistant) ? "Assistant" : "User"}`}
sr... | @@ -108,6 +109,7 @@ export function MessageTableEntry({ message, enabled, highlight, showAuthorBadge
const { t } = useTranslation(["message"]);
const router = useRouter();
+ const focusElementRef = useFocusElement<HTMLDivElement>(); | website/src/components/Messages/MessageTableEntry.tsx | 26 | TypeScript | 0.571 | suggestion | 173 | 51 | 51 | false | Scroll to message when loaded | 1,886 | LAION-AI/Open-Assistant | 29,137 | Python | notmd | johnflux | Review this pull request change.
Language: TypeScript
File: website/src/components/Messages/MessageTableEntry.tsx
PR Title: Scroll to message when loaded
BEFORE CODE: mt={inlineAvatar ? 0 : `6px`}
mb={inlineAvatar ? 1.5 : 0}
name={`${boolean(message.is_assistant) ? "Assistant" : "User"}`}
... | We only want to scroll on /messages/[id] and /admin/messages/[id] pages. Can you add another prop `scrollToHightlighted` or something similar? It should be false by default. | 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. |
op.create_table(
"worker_compliance_check",
sa.Column("id", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("worker_id", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("start_time", sa.DateTime(), nullable=False),
sa.Column("end_time", sa.DateTi... | I am not sure why Alembic generated this as I don't think this PR should have made any change affecting this. If anyone can confirm what might have caused this, we might want to remove it? | op.create_table(
"worker_compliance_check",
sa.Column("id", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("worker_id", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("compare_worker_id", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.... | @@ -0,0 +1,52 @@
+"""Add worker compliance checks to db
+
+Revision ID: a2865908a537
+Revises: e7a4bffb424c
+Create Date: 2023-02-26 13:28:25.181340
+
+"""
+import sqlalchemy as sa
+import sqlmodel
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision = "a2865908a537"
+down_revision = "e7a4bffb4... | inference/server/alembic/versions/2023_02_26_1328-a2865908a537_add_worker_compliance_checks_to_db.py | 26 | Python | 0.429 | question | 188 | 33 | 41 | false | Store worker compliance check results, add initial scoring algorithm | 1,894 | LAION-AI/Open-Assistant | 29,137 | Python | olliestanley | olliestanley | Review this pull request change.
Language: Python
File: inference/server/alembic/versions/2023_02_26_1328-a2865908a537_add_worker_compliance_checks_to_db.py
PR Title: Store worker compliance check results, add initial scoring algorithm
BEFORE CODE: op.create_table(
"worker_compliance_check",
sa.... | I am not sure why Alembic generated this as I don't think this PR should have made any change affecting this. If anyone can confirm what might have caused this, we might want to remove 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.session.add(message)
self.maybe_commit()
logger.debug(f"Added prompter message {len(content)=} to chat {chat_id}")
self.session.refresh(message)
return message
def initiate_assistant_message(self, parent_id: str, work_parameters: inference.WorkParameters) -> ... | If we are returning message can we add the type hint here as `models.DbMessage` | )
self.session.add(message)
self.maybe_commit()
logger.debug(f"Added prompter message {len(content)=} to chat {chat_id}")
self.session.refresh(message)
return message
def initiate_assistant_message(self, parent_id: str, work_parameters: inference.WorkParameters) -> ... | @@ -108,17 +108,12 @@ def initiate_assistant_message(self, parent_id: str, work_parameters: inference.
self.session.refresh(message)
return message
- def add_vote(self, message_id: str, score: int) -> models.DbVote:
- logger.info(f"Adding vote to {message_id=}: {score=}")
+ def update_s... | inference/server/oasst_inference_server/user_chat_repository.py | 26 | Python | 0.5 | suggestion | 79 | 41 | 44 | false | refactor inference message score | 1,907 | LAION-AI/Open-Assistant | 29,137 | Python | olliestanley | notmd | Review this pull request change.
Language: Python
File: inference/server/oasst_inference_server/user_chat_repository.py
PR Title: refactor inference message score
BEFORE CODE: )
self.session.add(message)
self.maybe_commit()
logger.debug(f"Added prompter message {len(content)=} to ch... | If we are returning message can we add the type hint here as `models.DbMessage` | 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.maybe_commit()
logger.debug(f"Added prompter message {len(content)=} to chat {chat_id}")
self.session.refresh(message)
return message
def initiate_assistant_message(self, parent_id: str, work_parameters: inference.WorkParameters) -> models.DbMessage:
logger.info(f"Addi... | Is this the correct way to validate input in fastapi? Please correct me if I'm wrong |
self.maybe_commit()
logger.debug(f"Added prompter message {len(content)=} to chat {chat_id}")
self.session.refresh(message)
return message
def initiate_assistant_message(self, parent_id: str, work_parameters: inference.WorkParameters) -> models.DbMessage:
logger.info(f"Addi... | @@ -108,17 +108,15 @@ def initiate_assistant_message(self, parent_id: str, work_parameters: inference.
self.session.refresh(message)
return message
- def add_vote(self, message_id: str, score: int) -> models.DbVote:
- logger.info(f"Adding vote to {message_id=}: {score=}")
+ def update_s... | inference/server/oasst_inference_server/user_chat_repository.py | 26 | Python | 0.214 | bug | 84 | 42 | 42 | false | refactor inference message score | 1,907 | LAION-AI/Open-Assistant | 29,137 | Python | notmd | notmd | Review this pull request change.
Language: Python
File: inference/server/oasst_inference_server/user_chat_repository.py
PR Title: refactor inference message score
BEFORE CODE:
self.maybe_commit()
logger.debug(f"Added prompter message {len(content)=} to chat {chat_id}")
self.session.refresh(... | Is this the correct way to validate input in fastapi? Please correct me if I'm wrong | 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 { Avatar, AvatarProps, Box, BoxProps, HStack, useBreakpointValue, useColorModeValue } from "@chakra-ui/react";
import { forwardRef, lazy, PropsWithChildren, Suspense, useMemo } from "react";
const RenderedMarkdown = lazy(() => import("./RenderedMarkdown"));
export type BaseMessageEntryProps = PropsWithChildren... | maybe this could be simplified to
```tsx
BoxProps & {
content: string;
avatarProps: Pick<AvatarProps, "name" | "src">;
}
``` | import { Avatar, AvatarProps, Box, BoxProps, HStack, useBreakpointValue, useColorModeValue } from "@chakra-ui/react";
import { forwardRef, lazy, Suspense, useMemo } from "react";
const RenderedMarkdown = lazy(() => import("./RenderedMarkdown"));
export type BaseMessageEntryProps = BoxProps & {
content: string;
av... | @@ -0,0 +1,60 @@
+import { Avatar, AvatarProps, Box, BoxProps, HStack, useBreakpointValue, useColorModeValue } from "@chakra-ui/react";
+import { forwardRef, lazy, PropsWithChildren, Suspense, useMemo } from "react";
+
+const RenderedMarkdown = lazy(() => import("./RenderedMarkdown"));
+
+export type BaseMessageEntryPr... | website/src/components/Messages/BaseMessageEntry.tsx | 10 | TypeScript | 0.786 | suggestion | 135 | 35 | 35 | false | Chat vote UI | 1,913 | LAION-AI/Open-Assistant | 29,137 | Python | AbdBarho | notmd | Review this pull request change.
Language: TypeScript
File: website/src/components/Messages/BaseMessageEntry.tsx
PR Title: Chat vote UI
BEFORE CODE: import { Avatar, AvatarProps, Box, BoxProps, HStack, useBreakpointValue, useColorModeValue } from "@chakra-ui/react";
import { forwardRef, lazy, PropsWithChildren, Sus... | maybe this could be simplified to
```tsx
BoxProps & {
content: string;
avatarProps: Pick<AvatarProps, "name" | "src">;
}
``` | 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. |
) -> List[Message]:
qry = db.query(Message)
if message_tree_id:
qry = qry.filter(Message.message_tree_id == message_tree_id)
if user_id:
qry = qry.filter(Message.user_id == user_id)
if deleted is not None:
qry = qry.filter(Message.deleted == deleted)
if prompts_only:
... | (We have to test this with the the production db size, I had similar code before for labels which I re-wrote after the query took > 0.5h to execute for 100k messages .. i.e. `fetch_tree_messages_and_avg_labels` function does the join now directly ...) | ) -> List[Message]:
qry = db.query(Message)
if message_tree_id:
qry = qry.filter(Message.message_tree_id == message_tree_id)
if user_id:
qry = qry.filter(Message.user_id == user_id)
if deleted is not None:
qry = qry.filter(Message.deleted == deleted)
if prompts_only:
... | @@ -59,10 +72,45 @@ def fetch_tree_messages(
qry = qry.filter(not_(Message.review_result), Message.review_count > 2)
elif review_result is True:
qry = qry.filter(Message.review_result)
+ if limit is not None and limit > 0:
+ qry = qry.limit(limit)
return qry.all()
+def get_ev... | backend/export.py | 26 | Python | 0.571 | suggestion | 251 | 51 | 51 | false | Extended export script | 1,954 | LAION-AI/Open-Assistant | 29,137 | Python | andreaskoepf | yk | Review this pull request change.
Language: Python
File: backend/export.py
PR Title: Extended export script
BEFORE CODE: ) -> List[Message]:
qry = db.query(Message)
if message_tree_id:
qry = qry.filter(Message.message_tree_id == message_tree_id)
if user_id:
qry = qry.filter(Message.user_... | (We have to test this with the the production db size, I had similar code before for labels which I re-wrote after the query took > 0.5h to execute for 100k messages .. i.e. `fetch_tree_messages_and_avg_labels` function does the join now 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. |
key = "ranking"
payload: db_payload.RankingReactionPayload = reaction.payload.payload
event = ExportMessageEventRanking(
user_id=str(reaction.user_id),
ranking=payload.ranking,
ranked_message_ids=[str(id) for id ... | Why zero instead of `Optional[int] = None` ? Since everything is none-able in python I always use None to indicate 'not set' instead of a special in-domain value (which I would use in C style code) ... but is a matter of taste of course. | key = "ranking"
payload: db_payload.RankingReactionPayload = reaction.payload.payload
event = ExportMessageEventRanking(
user_id=str(reaction.user_id),
ranking=payload.ranking,
ranked_message_ids=[str(id) for id ... | @@ -71,6 +119,7 @@ def fetch_tree_messages_and_avg_labels(
prompts_only: bool = False,
lang: Optional[str] = None,
review_result: Optional[bool] = None,
+ limit: int = 0, | backend/export.py | 26 | Python | 0.643 | question | 237 | 51 | 51 | false | Extended export script | 1,954 | LAION-AI/Open-Assistant | 29,137 | Python | andreaskoepf | yk | Review this pull request change.
Language: Python
File: backend/export.py
PR Title: Extended export script
BEFORE CODE: key = "ranking"
payload: db_payload.RankingReactionPayload = reaction.payload.payload
event = ExportMessageEventRanking(
user_id... | Why zero instead of `Optional[int] = None` ? Since everything is none-able in python I always use None to indicate 'not set' instead of a special in-domain value (which I would use in C style code) ... but is a matter of taste of course. | 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 training_conf.fuse_gelu:
model = fuse_gelu(model)
output_dir = (
training_conf.output_dir
if training_conf.output_dir
else f"{training_conf.model_name}-{training_conf.log_dir}-finetuned"
)
args = TrainingArguments(
output_dir=output_dir,
num_train_ep... | float(training_conf.adam_epsilon) |
if training_conf.fuse_gelu:
model = fuse_gelu(model)
output_dir = (
training_conf.output_dir
if training_conf.output_dir
else f"{training_conf.model_name}-{training_conf.log_dir}-finetuned"
)
args = TrainingArguments(
output_dir=output_dir,
num_train_ep... | @@ -252,6 +252,9 @@ def argument_parsing(notebook=False, notebook_args=None):
gradient_accumulation_steps=training_conf.gradient_accumulation_steps,
per_device_train_batch_size=training_conf.per_device_train_batch_size,
per_device_eval_batch_size=training_conf.per_device_eval_batch_size,
+ ... | model/model_training/trainer_sft.py | 26 | Python | 0.071 | suggestion | 33 | 51 | 51 | false | Update hyperparameters to reflect InstructGPT | 1,966 | LAION-AI/Open-Assistant | 29,137 | Python | sanagno | dvruette | Review this pull request change.
Language: Python
File: model/model_training/trainer_sft.py
PR Title: Update hyperparameters to reflect InstructGPT
BEFORE CODE:
if training_conf.fuse_gelu:
model = fuse_gelu(model)
output_dir = (
training_conf.output_dir
if training_conf.output_dir
... | float(training_conf.adam_epsilon) | 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 { useSession } from "next-auth/react";
import { get } from "src/lib/api";
import { LeaderboardEntity, LeaderboardTimeFrame } from "src/types/Leaderboard";
import uswSWRImmutable from "swr/immutable";
export const useUserScore = () => {
const { status } = useSession();
const isLoggedIn = status === "authenti... | This should be `refreshInterval` right? Also can you add `keepPreviousData` to avoid flashing UI? | import { useSession } from "next-auth/react";
import { get } from "src/lib/api";
import { LeaderboardEntity, LeaderboardTimeFrame } from "src/types/Leaderboard";
import uswSWRImmutable from "swr/immutable";
export const useUserScore = () => {
const { status } = useSession();
const isLoggedIn = status === "authenti... | @@ -0,0 +1,18 @@
+import { useSession } from "next-auth/react";
+import { get } from "src/lib/api";
+import { LeaderboardEntity, LeaderboardTimeFrame } from "src/types/Leaderboard";
+import uswSWRImmutable from "swr/immutable";
+
+export const useUserScore = () => {
+ const { status } = useSession();
+ const isLogged... | website/src/hooks/ui/useUserScore.ts | 13 | TypeScript | 0.429 | question | 97 | 19 | 20 | false | Show user score in header | 1,969 | LAION-AI/Open-Assistant | 29,137 | Python | notmd | AbdBarho | Review this pull request change.
Language: TypeScript
File: website/src/hooks/ui/useUserScore.ts
PR Title: Show user score in header
BEFORE CODE: import { useSession } from "next-auth/react";
import { get } from "src/lib/api";
import { LeaderboardEntity, LeaderboardTimeFrame } from "src/types/Leaderboard";
import u... | This should be `refreshInterval` right? Also can you add `keepPreviousData` to avoid flashing UI? | 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. |
src: `${boolean(message.is_assistant) ? "/images/logos/logo.png" : "/images/temp-avatars/av1.jpg"}`,
}}
outline={highlight ? "2px solid black" : undefined}
outlineColor={highlightColor}
cursor={enabled ? "pointer" : undefined}
overflowX="auto"
onClick={handleOnC... | can we extract this into its own component? | }}
outline={highlight ? "2px solid black" : undefined}
outlineColor={highlightColor}
cursor={enabled ? "pointer" : undefined}
overflowX="auto"
onClick={handleOnClick}
>
<Flex justifyContent="space-between" mt="2" alignItems="center">
{showCreatedDa... | @@ -107,35 +111,54 @@ export const MessageTableEntry = forwardRef<HTMLDivElement, MessageTableEntryPro
overflowX="auto"
onClick={handleOnClick}
>
- <MessageInlineEmojiRow>
- <Badge variant="subtle" colorScheme="gray" fontSize="xx-small">
- {message.lang}
- </... | website/src/components/Messages/MessageTableEntry.tsx | 26 | TypeScript | 0.143 | refactor | 43 | 51 | 51 | false | show message create date | 1,978 | LAION-AI/Open-Assistant | 29,137 | Python | AbdBarho | notmd | Review this pull request change.
Language: TypeScript
File: website/src/components/Messages/MessageTableEntry.tsx
PR Title: show message create date
BEFORE CODE: src: `${boolean(message.is_assistant) ? "/images/logos/logo.png" : "/images/temp-avatars/av1.jpg"}`,
}}
outline={highlight ? "2p... | can we extract this into its own 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. |
const sx: SystemStyleObject = {
overflowX: "auto",
wordBreak: "break-word",
pre: {
width: "100%",
bg: "transparent",
},
code: {
before: {
content: `""`, // charka prose come with "`" by default
},
bg: "gray.300",
p: 0.5,
borderRadius: "2px",
_dark: {
bg: "gray.700",... | I was following github css here. Adding margin-top may cause a very big spacing here. | const sx: SystemStyleObject = {
overflowX: "auto",
wordBreak: "break-word",
pre: {
width: "100%",
bg: "transparent",
},
code: {
before: {
content: `""`, // charka prose come with "`" by default
},
bg: "gray.300",
p: 0.5,
borderRadius: "2px",
_dark: {
bg: "gray.700",... | @@ -42,16 +43,13 @@ const sx: SystemStyleObject = {
},
},
"p:only-child": {
+ whiteSpace: "pre-wrap",
my: 0, // ovoid margin when markdown only render 1 p tag
},
p: {
whiteSpace: "pre-wrap",
- mb: 4,
- fontSize: "md",
- fontWeight: "normal",
- lineHeight: 6, | website/src/components/Messages/RenderedMarkdown.tsx | 26 | TypeScript | 0.286 | suggestion | 85 | 51 | 51 | false | Use browser defaults for markdown lists | 1,999 | LAION-AI/Open-Assistant | 29,137 | Python | notmd | AbdBarho | Review this pull request change.
Language: TypeScript
File: website/src/components/Messages/RenderedMarkdown.tsx
PR Title: Use browser defaults for markdown lists
BEFORE CODE: const sx: SystemStyleObject = {
overflowX: "auto",
wordBreak: "break-word",
pre: {
width: "100%",
bg: "transparent",
},
co... | I was following github css here. Adding margin-top may cause a very big spacing 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. |
max_length=self.max_length,
return_offsets_mapping=True,
)
message_change_indices = np.cumsum([len(x) for x in messages[:-1]])
# for each token an integer indicating the index of the message it belongs to. Just to create the label mask.
# ... | this should not be required now | max_length = self.max_length
# append eos token to each messages
assert self.tokenizer.eos_token
messages = [m + self.tokenizer.eos_token for m in messages]
flatten_message = self.tokenizer(
"".join(messages),
max_length=m... | @@ -54,13 +64,20 @@ def __call__(self, features):
list(map(lambda x: x[1], flatten_message["offset_mapping"])), | model/model_training/custom_datasets/dialogue_collator.py | 26 | Python | 0.143 | suggestion | 31 | 51 | 51 | false | Add SFT params random_offset_probability, label_masking | 2,005 | LAION-AI/Open-Assistant | 29,137 | Python | sanagno | andreaskoepf | Review this pull request change.
Language: Python
File: model/model_training/custom_datasets/dialogue_collator.py
PR Title: Add SFT params random_offset_probability, label_masking
BEFORE CODE: max_length=self.max_length,
return_offsets_mapping=True,
)
message... | this should not be required now | 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. |
padding: Union[bool, str, PaddingStrategy] = True
max_length: Optional[int] = None
mix_length_threshold: Optional[int] = 256
mix_probability: Optional[int] = 0.6
pad_to_multiple_of: Optional[int] = None
samples_mixing: Optional[bool] = False
def __call__(self, features):
flatten_mes... | Did we converge to this? Using the end of prompt-reply the same as eos? Not totally against it if eveyone agrees | padding: Union[bool, str, PaddingStrategy] = True
max_length: Optional[int] = None
mix_length_threshold: Optional[int] = 256
mix_probability: Optional[float] = 0.6
pad_to_multiple_of: Optional[int] = None
samples_mixing: Optional[bool] = False
random_offset_probability: Optional[float] = 0.5... | @@ -29,18 +31,26 @@ def __call__(self, features):
for messages in features:
messages = list(messages)
- # Add a way for the model to terminate generation
- # When we predict the start of a new expected question, we want to be able to stop generation
- messages.ap... | model/model_training/custom_datasets/dialogue_collator.py | 26 | Python | 0.357 | suggestion | 112 | 51 | 51 | false | Add SFT params random_offset_probability, label_masking | 2,005 | LAION-AI/Open-Assistant | 29,137 | Python | sanagno | andreaskoepf | Review this pull request change.
Language: Python
File: model/model_training/custom_datasets/dialogue_collator.py
PR Title: Add SFT params random_offset_probability, label_masking
BEFORE CODE: padding: Union[bool, str, PaddingStrategy] = True
max_length: Optional[int] = None
mix_length_threshold: Option... | Did we converge to this? Using the end of prompt-reply the same as eos? Not totally against it if eveyone agrees | 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. |
This function creates a subtree of messages starting from given root message.
"""
if isinstance(message, UUID):
message = self.fetch_message(message)
desc = self.db.query(Message).filter(
Message.message_tree_id == message.message_tree_id, Message.depth > message... | Could you add python type annotation? | This function creates a subtree of messages starting from given root message.
"""
if isinstance(message, UUID):
message = self.fetch_message(message)
desc = self.db.query(Message).filter(
Message.message_tree_id == message.message_tree_id, Message.depth > message... | @@ -888,14 +888,27 @@ def fetch_message_with_max_children(self, message: Message | UUID) -> tuple[Mess
max_message = max(tree, key=lambda m: m.children_count)
return max_message, [m for m in tree if m.parent_id == max_message.id]
- def _add_user_emojis_all(self, qry: Query) -> list[Message]:
+ ... | backend/oasst_backend/prompt_repository.py | 26 | Python | 0.286 | question | 37 | 51 | 51 | false | add `include_user` params in /messages/cursor` endpoint | 2,021 | LAION-AI/Open-Assistant | 29,137 | Python | andreaskoepf | notmd | Review this pull request change.
Language: Python
File: backend/oasst_backend/prompt_repository.py
PR Title: add `include_user` params in /messages/cursor` endpoint
BEFORE CODE: This function creates a subtree of messages starting from given root message.
"""
if isinstance(message, UUID):
... | Could you add python type annotation? | 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. |
"GPT-JT": TokenizerConfig(special_tokens=SpecialTokens(sep_token="<|extratoken_100|>")),
"codegen": TokenizerConfig(special_tokens=SpecialTokens("<|endoftext|>", sep_token="<|endoftext|>")),
"pythia": TokenizerConfig(special_tokens=SpecialTokens("<|padding|>", "<|endoftext|>", "<|endoftext|>")),
}
def mat... | This should be Digits instead of Digit | "galactica": TokenizerConfig(special_tokens=SpecialTokens("<pad>", "</s>")),
"GPT-JT": TokenizerConfig(special_tokens=SpecialTokens(sep_token="<|extratoken_100|>")),
"codegen": TokenizerConfig(special_tokens=SpecialTokens("<|endoftext|>", sep_token="<|endoftext|>")),
"pythia": TokenizerConfig(special_to... | @@ -183,6 +184,9 @@ def get_tokenizer(conf) -> transformers.AutoTokenizer:
tokenizer = transformers.AutoTokenizer.from_pretrained(conf.model_name, cache_dir=conf.cache_dir)
tokenizer_config = match_tokenizer_name(conf.model_name)
+ if tokenizer_config.per_digit_tokens:
+ tokenizer._tokenizer.pre_p... | model/model_training/utils.py | 26 | Python | 0.143 | suggestion | 38 | 51 | 51 | false | Add option to tokenize numbers per digit | 2,024 | LAION-AI/Open-Assistant | 29,137 | Python | sanagno | johnflux | Review this pull request change.
Language: Python
File: model/model_training/utils.py
PR Title: Add option to tokenize numbers per digit
BEFORE CODE: "GPT-JT": TokenizerConfig(special_tokens=SpecialTokens(sep_token="<|extratoken_100|>")),
"codegen": TokenizerConfig(special_tokens=SpecialTokens("<|endoftext|... | This should be Digits instead of Digit | 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("--per-digit-tokens", action="store_true")
parser.set_defaults(deepspeed=False)
if notebook:
args, remaining = parser.p... | i would move this to the config.yaml instead of args | help="""
Multiple configs can be passed to set different options.
For example, run as:
./trainer_sft.py --configs galactica-125m webgpt_dataset_only per_digit_tokens
to run the galactica-125m model, using the webgpt dataset only (as opposed to all
the datasets listed... | @@ -189,6 +190,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
+ conf["per_digit_tokens"] = args.per_digit_tokens | model/model_training/trainer_sft.py | 26 | Python | 0.286 | refactor | 52 | 51 | 51 | false | Add option to tokenize numbers per digit | 2,024 | LAION-AI/Open-Assistant | 29,137 | Python | sanagno | johnflux | Review this pull request change.
Language: Python
File: model/model_training/trainer_sft.py
PR Title: Add option to tokenize numbers per digit
BEFORE CODE: parser.add_argument("--no-deepspeed", dest="deepspeed", action="store_false")
parser.add_argument("--wandb-entity", type=str, default="open-assistant")
... | i would move this to the config.yaml instead of args | 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 isAdminOrMod = useHasAnyRole(["admin", "moderator"]);
const columns: DataTableColumnDef<WindowLeaderboardEntity>[] = useMemo(
() => [
{
...columnHelper.accessor("rank", {
header: t("rank"),
cell: (ctx) =>
ctx.row.original.isSpaceRow ? (
<SpaceR... | We already have an effect in the `UserAvatar` component, so why do we need key here? |
const isAdminOrMod = useHasAnyRole(["admin", "moderator"]);
const columns: DataTableColumnDef<WindowLeaderboardEntity>[] = useMemo(
() => [
{
...columnHelper.accessor("rank", {
header: t("rank"),
cell: (ctx) =>
ctx.row.original.isSpaceRow ? (
<SpaceR... | @@ -63,18 +63,21 @@ export const LeaderboardTable = ({
},
columnHelper.accessor("display_name", {
header: t("user"),
- cell: ({ getValue, row }) => (
- <div className="flex flex-row items-center gap-2">
- <UserAvatar displayName={getValue()} avatarUrl={row.original.imag... | website/src/components/LeaderboardTable/LeaderboardTable.tsx | 26 | TypeScript | 0.429 | question | 84 | 51 | 51 | false | Show correct user avatars on leaderboard | 2,039 | LAION-AI/Open-Assistant | 29,137 | Python | notmd | AbdBarho | Review this pull request change.
Language: TypeScript
File: website/src/components/LeaderboardTable/LeaderboardTable.tsx
PR Title: Show correct user avatars on leaderboard
BEFORE CODE:
const isAdminOrMod = useHasAnyRole(["admin", "moderator"]);
const columns: DataTableColumnDef<WindowLeaderboardEntity>[] = us... | We already have an effect in the `UserAvatar` component, so why do we need key 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 { useCallback, useState } from "react";
export type CursorPaginationState = {
/**
* The user's `display_name` used for pagination.
*/
cursor: string;
/**
* The pagination direction.
*/
direction: "forward" | "back";
};
export const useCursorPagination = () => {
const [pagination, setPagi... | I know this does not make a difference, but `setPagination` should be a dependency. | import { useCallback, useState } from "react";
export type CursorPaginationState = {
/**
* The user's `display_name` used for pagination.
*/
cursor: string;
/**
* The pagination direction.
*/
direction: "forward" | "back";
};
export const useCursorPagination = () => {
const [pagination, setPagi... | @@ -10,26 +10,26 @@ export interface CursorPaginationState {
* The pagination direction.
*/
direction: "forward" | "back";
-}
+};
export const useCursorPagination = () => {
const [pagination, setPagination] = useState<CursorPaginationState>({ cursor: "", direction: "forward" });
- const toPreviousPa... | website/src/components/DataTable/useCursorPagination.ts | 23 | TypeScript | 0.429 | suggestion | 83 | 41 | 47 | false | Admin message list | 2,057 | LAION-AI/Open-Assistant | 29,137 | Python | AbdBarho | notmd | Review this pull request change.
Language: TypeScript
File: website/src/components/DataTable/useCursorPagination.ts
PR Title: Admin message list
BEFORE CODE: import { useCallback, useState } from "react";
export type CursorPaginationState = {
/**
* The user's `display_name` used for pagination.
*/
cursor... | I know this does not make a difference, but `setPagination` should be a dependency. | 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 { useCallback, useState } from "react";
export type CursorPaginationState = {
/**
* The user's `display_name` used for pagination.
*/
cursor: string;
/**
* The pagination direction.
*/
direction: "forward" | "back";
};
export const useCursorPagination = () => {
const [pagination, setPagi... | is it possible to use `data?: { prev?: string; next?: string }` | import { useCallback, useState } from "react";
export type CursorPaginationState = {
/**
* The user's `display_name` used for pagination.
*/
cursor: string;
/**
* The pagination direction.
*/
direction: "forward" | "back";
};
export const useCursorPagination = () => {
const [pagination, setPagi... | @@ -10,26 +10,26 @@ export interface CursorPaginationState {
* The pagination direction.
*/
direction: "forward" | "back";
-}
+};
export const useCursorPagination = () => {
const [pagination, setPagination] = useState<CursorPaginationState>({ cursor: "", direction: "forward" });
- const toPreviousPa... | website/src/components/DataTable/useCursorPagination.ts | 18 | TypeScript | 0.429 | suggestion | 63 | 41 | 43 | false | Admin message list | 2,057 | LAION-AI/Open-Assistant | 29,137 | Python | AbdBarho | notmd | Review this pull request change.
Language: TypeScript
File: website/src/components/DataTable/useCursorPagination.ts
PR Title: Admin message list
BEFORE CODE: import { useCallback, useState } from "react";
export type CursorPaginationState = {
/**
* The user's `display_name` used for pagination.
*/
cursor... | is it possible to use `data?: { prev?: string; next?: 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 useSWRImmutable from "swr/immutable";
import { DataTable, DataTableRowPropsCallback } from "../DataTable/DataTable";
import { DataTableAction } from "../DataTable/DataTableAction";
import { useCursorPagination } from "../DataTable/useCursorPagination";
import { UserDisplayNameCell } from "../UserDisplayNameCell... | it is not clear to me what the variable `includeUser` means? to also include the user profile in the datat returned by the API call? | import useSWRImmutable from "swr/immutable";
import { DataTable, DataTableRowPropsCallback } from "../DataTable/DataTable";
import { DataTableAction } from "../DataTable/DataTableAction";
import { useCursorPagination } from "../DataTable/useCursorPagination";
import { UserDisplayNameCell } from "../UserDisplayNameCell... | @@ -42,45 +49,87 @@ const DateDiff = ({ children }: { children: string | Date | number }) => {
);
};
-export const AdminMessageTable = (props: StrictOmit<DataTableProps<Message>, "columns">) => {
+export const AdminMessageTable = ({ userId, includeUser }: { userId?: string; includeUser?: boolean }) => { | website/src/components/Messages/AdminMessageTable.tsx | 26 | TypeScript | 0.571 | question | 132 | 51 | 51 | false | Admin message list | 2,057 | LAION-AI/Open-Assistant | 29,137 | Python | AbdBarho | notmd | Review this pull request change.
Language: TypeScript
File: website/src/components/Messages/AdminMessageTable.tsx
PR Title: Admin message list
BEFORE CODE: import useSWRImmutable from "swr/immutable";
import { DataTable, DataTableRowPropsCallback } from "../DataTable/DataTable";
import { DataTableAction } from "..... | it is not clear to me what the variable `includeUser` means? to also include the user profile in the datat returned by the API call? | 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 columnHelper = createColumnHelper<
Message & {
isActive?: boolean;
}
>();
// TODO move this to somewhere
const DateDiff = ({ children }: { children: string | Date | number }) => {
const date = new Date(children);
const diff = formatDistanceToNow(date, { addSuffix: true });
return (
<Tooltip lab... | would be great to rename `mutate` to something that reflects the actual behavior. | const columnHelper = createColumnHelper<
Message & {
isActive?: boolean;
}
>();
// TODO move this to somewhere
const DateDiff = ({ children }: { children: string | Date | number }) => {
const date = new Date(children);
const diff = formatDistanceToNow(date, { addSuffix: true });
return (
<Tooltip lab... | @@ -42,45 +49,87 @@ const DateDiff = ({ children }: { children: string | Date | number }) => {
);
};
-export const AdminMessageTable = (props: StrictOmit<DataTableProps<Message>, "columns">) => {
+export const AdminMessageTable = ({ userId, includeUser }: { userId?: string; includeUser?: boolean }) => {
const ... | website/src/components/Messages/AdminMessageTable.tsx | 26 | TypeScript | 0.429 | suggestion | 81 | 51 | 51 | false | Admin message list | 2,057 | LAION-AI/Open-Assistant | 29,137 | Python | AbdBarho | notmd | Review this pull request change.
Language: TypeScript
File: website/src/components/Messages/AdminMessageTable.tsx
PR Title: Admin message list
BEFORE CODE: const columnHelper = createColumnHelper<
Message & {
isActive?: boolean;
}
>();
// TODO move this to somewhere
const DateDiff = ({ children }: { childr... | would be great to rename `mutate` to something that reflects the actual behavior. | 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. |
{!row.original.deleted && (
<DataTableAction
onClick={() => {
setDeleteMessageId(id);
onOpen();
}}
icon={Trash}
aria-label="Delete message"
isLoading={isMutatin... | `setActiveMessageId` as dependency? | <DataTableAction
onClick={() => {
setDeleteMessageId(id);
onOpen();
}}
icon={Trash}
aria-label="Delete message"
isLoading={isMutating && deleteMessageId === id}
... | @@ -152,7 +204,14 @@ export const AdminMessageTable = (props: StrictOmit<DataTableProps<Message>, "co
}, [deleteMessageId, isMutating, onOpen]);
const { t } = useTranslation(["common", "message"]);
-
+ const rowProps: DataTableRowPropsCallback<Message> = useCallback((row) => {
+ return {
+ onClick: () ... | website/src/components/Messages/AdminMessageTable.tsx | 26 | TypeScript | 0.214 | question | 36 | 51 | 51 | false | Admin message list | 2,057 | LAION-AI/Open-Assistant | 29,137 | Python | AbdBarho | notmd | Review this pull request change.
Language: TypeScript
File: website/src/components/Messages/AdminMessageTable.tsx
PR Title: Admin message list
BEFORE CODE: {!row.original.deleted && (
<DataTableAction
onClick={() => {
setDeleteMessageId(id);
... | `setActiveMessageId` as dependency? | 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. |
<>
<Head>
<title>Open Assistant</title>
</Head>
<AdminArea>
<Card>
<CardBody>
<AdminMessageTable includeUser></AdminMessageTable>
</CardBody>
</Card>
</AdminArea>
</>
);
};
MessageList.getLayout = getAdminLayout;
export default ... | would this work? https://github.com/LAION-AI/Open-Assistant/blob/3c4bf803b1e50d27cb767593433235ddb033662f/website/src/pages/messages/index.tsx#L8 | import { Card, CardBody } from "@chakra-ui/react";
import Head from "next/head";
import { AdminArea } from "src/components/AdminArea";
import { getAdminLayout } from "src/components/Layout";
import { AdminMessageTable } from "src/components/Messages/AdminMessageTable";
export { getDefaultStaticProps as getStaticProps }... | @@ -0,0 +1,36 @@
+import { Card, CardBody } from "@chakra-ui/react";
+import { GetServerSideProps } from "next";
+import Head from "next/head";
+import { serverSideTranslations } from "next-i18next/serverSideTranslations";
+import { AdminArea } from "src/components/AdminArea";
+import { getAdminLayout } from "src/compo... | website/src/pages/admin/messages/index.tsx | 26 | TypeScript | 0.357 | suggestion | 145 | 27 | 28 | false | Admin message list | 2,057 | LAION-AI/Open-Assistant | 29,137 | Python | AbdBarho | notmd | Review this pull request change.
Language: TypeScript
File: website/src/pages/admin/messages/index.tsx
PR Title: Admin message list
BEFORE CODE: <>
<Head>
<title>Open Assistant</title>
</Head>
<AdminArea>
<Card>
<CardBody>
<AdminMessageTable includeUser></... | would this work? https://github.com/LAION-AI/Open-Assistant/blob/3c4bf803b1e50d27cb767593433235ddb033662f/website/src/pages/messages/index.tsx#L8 | 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. |
frontend_user: deps.FrontendUserId = Depends(deps.get_frontend_user_id),
api_client: ApiClient = Depends(deps.get_api_client),
db: Session = Depends(deps.get_db),
):
"""
Get message with the most children from the tree of the provided message.
"""
pr = PromptRepository(db, api_client, fronte... | Could we call the command "restore" or simply "undelete"?
and maybe add `response_model=None,` to explicitly show that it does not return anything. | frontend_user: deps.FrontendUserId = Depends(deps.get_frontend_user_id),
api_client: ApiClient = Depends(deps.get_api_client),
db: Session = Depends(deps.get_db),
):
"""
Get message with the most children from the tree of the provided message.
"""
pr = PromptRepository(db, api_client, fronte... | @@ -325,7 +325,19 @@ def mark_message_deleted(
pr.mark_messages_deleted(message_id)
-@router.post("/{message_id}/emoji", response_model=protocol.Message)
+@router.put("/{message_id}/reintroduce", status_code=HTTP_202_ACCEPTED) | backend/oasst_backend/api/v1/messages.py | 26 | Python | 0.571 | suggestion | 148 | 51 | 51 | false | [#2077] Possbility to revert message deletion | 2,079 | LAION-AI/Open-Assistant | 29,137 | Python | andreaskoepf | Shadowner | Review this pull request change.
Language: Python
File: backend/oasst_backend/api/v1/messages.py
PR Title: [#2077] Possbility to revert message deletion
BEFORE CODE: frontend_user: deps.FrontendUserId = Depends(deps.get_frontend_user_id),
api_client: ApiClient = Depends(deps.get_api_client),
db: Session... | Could we call the command "restore" or simply "undelete"?
and maybe add `response_model=None,` to explicitly show that it does not return anything. | 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. |
message_id = None
if isinstance(message, UUID):
message_id = message
elif isinstance(message, Message):
message_id = message.id
else:
raise OasstError("Server error", OasstErrorCode.SERVER_ERROR1, HTTPStatus.INTERNAL_SERVER_ERROR)
query = upda... | Not exactly sure what this does .. it traces upwards to the root of the tree? | if isinstance(message, UUID):
message_id = message
elif isinstance(message, Message):
message_id = message.id
else:
raise OasstError("Server error", OasstErrorCode.SERVER_ERROR1, HTTPStatus.INTERNAL_SERVER_ERROR)
query = update(Message).where(Message.... | @@ -1069,6 +1069,39 @@ def mark_messages_deleted(self, messages: Message | UUID | list[Message | UUID],
parent_ids = self.db.execute(query).scalars().all()
+ @managed_tx_method(CommitMode.COMMIT)
+ def reintroduce_deleted_message(self, message: Message | UUID, recursive: bool = True):
+ ... | backend/oasst_backend/prompt_repository.py | 26 | Python | 0.214 | question | 77 | 51 | 51 | false | [#2077] Possbility to revert message deletion | 2,079 | LAION-AI/Open-Assistant | 29,137 | Python | andreaskoepf | Shadowner | Review this pull request change.
Language: Python
File: backend/oasst_backend/prompt_repository.py
PR Title: [#2077] Possbility to revert message deletion
BEFORE CODE: message_id = None
if isinstance(message, UUID):
message_id = message
elif isinstance(message, Message):
... | Not exactly sure what this does .. it traces upwards to the root of the tree? | 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. |
update(Message).filter(Message.parent_id.in_(parent_ids)).values(deleted=True).returning(Message.id)
)
parent_ids = self.db.execute(query).scalars().all()
@managed_tx_method(CommitMode.COMMIT)
def reintroduce_deleted_message(self, message: Message | UUID, re... | `Message.id == message` looks a bit strange, should it be `message_id`? Do you want to undelete all descendants? The easiest would be to use the `fetch_message_descendants()` method and use ORM to set deleted = False .. usually message trees have <100 messages. | update(Message).filter(Message.parent_id.in_(parent_ids)).values(deleted=True).returning(Message.id)
)
parent_ids = self.db.execute(query).scalars().all()
@managed_tx_method(CommitMode.COMMIT)
def undelete_deleted_message(self, message: Message | UUID):
... | @@ -1069,6 +1069,39 @@ def mark_messages_deleted(self, messages: Message | UUID | list[Message | UUID],
parent_ids = self.db.execute(query).scalars().all()
+ @managed_tx_method(CommitMode.COMMIT)
+ def reintroduce_deleted_message(self, message: Message | UUID, recursive: bool = True):
+ ... | backend/oasst_backend/prompt_repository.py | 26 | Python | 0.643 | suggestion | 261 | 51 | 51 | false | [#2077] Possbility to revert message deletion | 2,079 | LAION-AI/Open-Assistant | 29,137 | Python | andreaskoepf | Shadowner | Review this pull request change.
Language: Python
File: backend/oasst_backend/prompt_repository.py
PR Title: [#2077] Possbility to revert message deletion
BEFORE CODE: update(Message).filter(Message.parent_id.in_(parent_ids)).values(deleted=True).returning(Message.id)
)
... | `Message.id == message` looks a bit strange, should it be `message_id`? Do you want to undelete all descendants? The easiest would be to use the `fetch_message_descendants()` method and use ORM to set deleted = False .. usually message trees have <100 messages. | 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. |
message, children = pr.fetch_message_with_max_children(message.message_tree_id)
return utils.prepare_tree([message, *children], message.id)
@router.delete("/{message_id}", status_code=HTTP_204_NO_CONTENT)
def mark_message_deleted(
*,
message_id: UUID,
frontend_user: deps.FrontendUserId = Depends(d... | The recursive param should be exposed in the api vi a query param (maybe default true). | message, children = pr.fetch_message_with_max_children(message.message_tree_id)
return utils.prepare_tree([message, *children], message.id)
@router.delete("/{message_id}", status_code=HTTP_204_NO_CONTENT)
def mark_message_deleted(
*,
message_id: UUID,
frontend_user: deps.FrontendUserId = Depends(d... | @@ -325,7 +325,19 @@ def mark_message_deleted(
pr.mark_messages_deleted(message_id)
-@router.post("/{message_id}/emoji", response_model=protocol.Message)
+@router.put("/{message_id}/reintroduce", status_code=HTTP_202_ACCEPTED)
+def reintroduce_message(
+ *,
+ message_id: UUID,
+ frontend_user: deps.Fr... | backend/oasst_backend/api/v1/messages.py | 26 | Python | 0.286 | suggestion | 88 | 46 | 46 | false | [#2077] Possbility to revert message deletion | 2,079 | LAION-AI/Open-Assistant | 29,137 | Python | andreaskoepf | Shadowner | Review this pull request change.
Language: Python
File: backend/oasst_backend/api/v1/messages.py
PR Title: [#2077] Possbility to revert message deletion
BEFORE CODE: message, children = pr.fetch_message_with_max_children(message.message_tree_id)
return utils.prepare_tree([message, *children], message.id)
... | The recursive param should be exposed in the api vi a query param (maybe default true). | 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. |
"""
These are in the form of 'INSTRUCTION', 'RESPONSE'
"""
from custom_datasets.formatting import format_pairs
from datasets import load_dataset
from torch.utils.data import Dataset
INSTRUCTION_DATASETS = {
# Note humaneval_mbpp_codegen_qa returns a code string that we would want to at least wrap in ``` marks`... | remove this for new formatting | """
These are in the form of 'INSTRUCTION', 'RESPONSE'
"""
from datasets import load_dataset
from torch.utils.data import Dataset
INSTRUCTION_DATASETS = {
# Note humaneval_mbpp_codegen_qa returns a code string that we would want to at least wrap in ``` marks`
"humaneval_mbpp_codegen_qa": "OllieStanley/huma... | @@ -1,7 +1,7 @@
"""
These are in the form of 'INSTRUCTION', 'RESPONSE'
"""
-from custom_datasets.formatting import format_pair
+from custom_datasets.formatting import format_pairs | model/model_training/custom_datasets/instruction.py | 4 | Python | 0.143 | refactor | 30 | 29 | 29 | false | Add minimath support | 2,094 | LAION-AI/Open-Assistant | 29,137 | Python | sanagno | johnflux | Review this pull request change.
Language: Python
File: model/model_training/custom_datasets/instruction.py
PR Title: Add minimath support
BEFORE CODE: """
These are in the form of 'INSTRUCTION', 'RESPONSE'
"""
from custom_datasets.formatting import format_pairs
from datasets import load_dataset
from torch.util... | remove this for new formatting | 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. |
"humaneval_mbpp_testgen_qa": "OllieStanley/humaneval-mbpp-testgen-qa",
"grade_school_math_instructions": "qwedsacf/grade-school-math-instructions",
"recipes": "dctanner/oa_recipes",
"ubuntu_dialogue_qa": "sedthh/ubuntu_dialogue_qa",
"cmu_wiki_qa": "sedthh/cmu_wiki_qa",
"youtube_subs_howto100M": ... | replace with
`return (data[self.instruction_column], data[self.response_column])` | "grade_school_math_instructions": "qwedsacf/grade-school-math-instructions",
"recipes": "dctanner/oa_recipes",
"ubuntu_dialogue_qa": "sedthh/ubuntu_dialogue_qa",
"cmu_wiki_qa": "sedthh/cmu_wiki_qa",
"youtube_subs_howto100M": "totuta/youtube_subs_howto100M",
"iapp_wiki_qa_squad": "wannaphong/iapp... | @@ -17,20 +17,21 @@
"youtube_subs_howto100M": "totuta/youtube_subs_howto100M",
"iapp_wiki_qa_squad": "wannaphong/iapp_wiki_qa_squad_oa",
"zhihu-kol": "wangrui6/zhihu-kol",
+ "minimath": "kentsui/minimath",
}
class InstructionDataset(Dataset):
def __init__(self, dataset, cache_dir, split, ma... | model/model_training/custom_datasets/instruction.py | 26 | Python | 0.429 | suggestion | 83 | 27 | 26 | false | Add minimath support | 2,094 | LAION-AI/Open-Assistant | 29,137 | Python | sanagno | johnflux | Review this pull request change.
Language: Python
File: model/model_training/custom_datasets/instruction.py
PR Title: Add minimath support
BEFORE CODE: "humaneval_mbpp_testgen_qa": "OllieStanley/humaneval-mbpp-testgen-qa",
"grade_school_math_instructions": "qwedsacf/grade-school-math-instructions",
"rec... | replace with
`return (data[self.instruction_column], data[self.response_column])` | 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. |
out = flash_attn(qkv, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen)
# out: [bs, seq_len, num_attention_heads, attn_head_size]
if attention_mask is not None:
seqs = [out[start:end] for start, end in zip(cu_seqlens[:-1], cu_seqlens[1:])]
out = pad_sequence(seqs, batch_first=True)
# r... | typo from my side:
```suggestion
- `output_attentions=True` does not work after patching, attention weights will be None
``` |
out = flash_attn(qkv, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen)
# out: [bs, seq_len, num_attention_heads, attn_head_size]
if attention_mask is not None:
seqs = [out[start:end] for start, end in zip(cu_seqlens[:-1], cu_seqlens[1:])]
out = pad_sequence(seqs, batch_first=True)
# r... | @@ -79,7 +80,7 @@ def add_flash_attn(module: nn.Module, causal: bool = True):
Limitations:
- Only works for fp16 or bf16 inputs
- Requires inputs to be on CUDA
- - `outptu_attentions=True` does work after patching, attention weights will be None
+ - `output_attentions=True` does work after ... | model/model_training/models/patching.py | 26 | Python | 0.714 | suggestion | 134 | 51 | 51 | false | Add minimath support | 2,094 | LAION-AI/Open-Assistant | 29,137 | Python | dvruette | johnflux | Review this pull request change.
Language: Python
File: model/model_training/models/patching.py
PR Title: Add minimath support
BEFORE CODE:
out = flash_attn(qkv, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen)
# out: [bs, seq_len, num_attention_heads, attn_head_size]
if attention_mask is not None:
... | typo from my side:
```suggestion
- `output_attentions=True` does not work after patching, attention weights will be None
``` | 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 (
<>
<Head>
<title>Who are we - Open Assistant</title>
<meta name="description" content="The team begind Open Assistant" />
</Head>
<Box fontFamily="Inter" p="6" className="oa-basic-theme">
<Box className="max-w-6xl mx-auto">
<Card>
<CardBody ... | ```suggestion
<Avatar src={imageURL} loading="lazy"/>
``` | return (
<>
<Head>
<title>Who are we - Open Assistant</title>
<meta name="description" content="The team begind Open Assistant" />
</Head>
<Box fontFamily="Inter" p="6" className="oa-basic-theme">
<Box className="max-w-6xl mx-auto">
<Card>
<CardBody ... | @@ -0,0 +1,66 @@
+export { getDefaultStaticProps as getStaticProps } from "src/lib/default_static_props";
+import { Avatar, Badge, Box, Card, CardBody, Flex, Grid, Heading, Text } from "@chakra-ui/react";
+import { Github } from "lucide-react";
+import Head from "next/head";
+import Link from "next/link";
+import React... | website/src/pages/team.tsx | 26 | TypeScript | 0.571 | suggestion | 85 | 51 | 51 | false | Add Team page | 2,103 | LAION-AI/Open-Assistant | 29,137 | Python | notmd | AbdBarho | Review this pull request change.
Language: TypeScript
File: website/src/pages/team.tsx
PR Title: Add Team page
BEFORE CODE: return (
<>
<Head>
<title>Who are we - Open Assistant</title>
<meta name="description" content="The team begind Open Assistant" />
</Head>
<Box fontFami... | ```suggestion
<Avatar src={imageURL} loading="lazy"/>
``` | 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 sliderItems = [
{
key: "temperature",
},
{
key: "max_new_tokens",
max: 1000,
step: 1,
min: 1,
},
{
key: "top_p",
},
{
key: "repetition_penalty",
min: 1,
max: 2,
},
{
key: "top_k",
min: 1,
max: 2,
},
] as const;
const ChatConfigForm = ({... | I'm not sure about the range of these parameters. But for `repetition_penalty` and `top_k` it should be greater than 1 otherwise the inference backend will crash | import { FormProvider, useForm } from "react-hook-form";
import { WorkParametersInput } from "src/types/Chat";
import { ChatConfigDrawer } from "./ChatConfigDrawer";
import { useChatContext } from "./ChatContext";
import { ChatConversation } from "./ChatConversation";
export const ChatSection = ({ chatId }: { chatId:... | @@ -0,0 +1,212 @@
+import {
+ CircularProgress,
+ Drawer,
+ DrawerBody,
+ DrawerCloseButton,
+ DrawerContent,
+ DrawerHeader,
+ DrawerOverlay,
+ Flex,
+ FormControl,
+ FormLabel,
+ IconButton,
+ NumberDecrementStepper,
+ NumberIncrementStepper,
+ NumberInput,
+ NumberInputField,
+ NumberInputStepper,
+ ... | website/src/components/Chat/ChatSection.tsx | 26 | TypeScript | 0.571 | bug | 161 | 51 | 21 | false | Chat config UI | 2,115 | LAION-AI/Open-Assistant | 29,137 | Python | notmd | notmd | Review this pull request change.
Language: TypeScript
File: website/src/components/Chat/ChatSection.tsx
PR Title: Chat config UI
BEFORE CODE: );
};
const sliderItems = [
{
key: "temperature",
},
{
key: "max_new_tokens",
max: 1000,
step: 1,
min: 1,
},
{
key: "top_p",
},
{
... | I'm not sure about the range of these parameters. But for `repetition_penalty` and `top_k` it should be greater than 1 otherwise the inference backend will crash | 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. |
SliderTrack,
Stack,
useDisclosure,
} from "@chakra-ui/react";
import { Settings } from "lucide-react";
import { useTranslation } from "next-i18next";
import { useCallback, useState } from "react";
import { Controller, useForm, UseFormReturn } from "react-hook-form";
import { get } from "src/lib/api";
import { API... | Here are the default params. I just fill them randomly, please suggest | import { FormProvider, useForm } from "react-hook-form";
import { WorkParametersInput } from "src/types/Chat";
import { ChatConfigDrawer } from "./ChatConfigDrawer";
import { useChatContext } from "./ChatContext";
import { ChatConversation } from "./ChatConversation";
export const ChatSection = ({ chatId }: { chatId:... | @@ -0,0 +1,212 @@
+import {
+ CircularProgress,
+ Drawer,
+ DrawerBody,
+ DrawerCloseButton,
+ DrawerContent,
+ DrawerHeader,
+ DrawerOverlay,
+ Flex,
+ FormControl,
+ FormLabel,
+ IconButton,
+ NumberDecrementStepper,
+ NumberIncrementStepper,
+ NumberInput,
+ NumberInputField,
+ NumberInputStepper,
+ ... | website/src/components/Chat/ChatSection.tsx | 26 | TypeScript | 0.214 | suggestion | 70 | 51 | 21 | false | Chat config UI | 2,115 | LAION-AI/Open-Assistant | 29,137 | Python | notmd | notmd | Review this pull request change.
Language: TypeScript
File: website/src/components/Chat/ChatSection.tsx
PR Title: Chat config UI
BEFORE CODE: SliderTrack,
Stack,
useDisclosure,
} from "@chakra-ui/react";
import { Settings } from "lucide-react";
import { useTranslation } from "next-i18next";
import { useCallba... | Here are the default params. I just fill them randomly, please suggest | 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 { createContext, PropsWithChildren, useContext, useMemo } from "react";
import { ModelInfo } from "src/types/Chat";
export type ChatContext = {
modelInfos: ModelInfo[];
};
const chatContext = createContext<ChatContext>({} as ChatContext);
export const useChatContext = () => useContext(chatContext);
export ... | does this make any difference? | import { createContext, PropsWithChildren, useContext, useMemo } from "react";
import { ModelInfo } from "src/types/Chat";
export type ChatContext = {
modelInfos: ModelInfo[];
};
const chatContext = createContext<ChatContext>({} as ChatContext);
export const useChatContext = () => useContext(chatContext);
export ... | @@ -0,0 +1,16 @@
+import { createContext, PropsWithChildren, useContext, useMemo } from "react";
+import { ModelInfo } from "src/types/Chat";
+
+export type ChatContext = {
+ modelInfos: ModelInfo[];
+};
+
+const chatContext = createContext<ChatContext>({} as ChatContext);
+
+export const useChatContext = () => useCon... | website/src/components/Chat/ChatContext.tsx | 13 | TypeScript | 0.071 | question | 30 | 17 | 22 | false | Chat config UI | 2,115 | LAION-AI/Open-Assistant | 29,137 | Python | AbdBarho | notmd | Review this pull request change.
Language: TypeScript
File: website/src/components/Chat/ChatContext.tsx
PR Title: Chat config UI
BEFORE CODE: import { createContext, PropsWithChildren, useContext, useMemo } from "react";
import { ModelInfo } from "src/types/Chat";
export type ChatContext = {
modelInfos: ModelInf... | does this make any difference? | 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 Head from "next/head";
import Link from "next/link";
import { useTranslation } from "next-i18next";
import React from "react";
import { getTransparentHeaderLayout } from "src/components/Layout";
import data from "../data/team.json";
const Team = () => {
const cardBackgroundColor = useColorModeValue("gray.100... | There is Card and CardBody components for this | Badge,
Box,
Card,
CardBody,
Flex,
Grid,
Heading,
Stack,
Text,
useColorModeValue,
} from "@chakra-ui/react";
import { Github } from "lucide-react";
import Head from "next/head";
import Link from "next/link";
import { useTranslation } from "next-i18next";
import React from "react";
import { getTranspa... | @@ -19,45 +21,43 @@ const Team = () => {
<meta name="description" content="The team begind Open Assistant" />
</Head>
<Box fontFamily="Inter" p="6" className="oa-basic-theme">
- <Box className="max-w-6xl mx-auto">
- <Card>
- <CardBody display="flex" flexDirection={"colu... | website/src/pages/team.tsx | 26 | TypeScript | 0.071 | suggestion | 46 | 51 | 51 | false | Updated team page to fit visually more the the rest of the pages, added a button to the call-to-action section which links to the team page. | 2,126 | LAION-AI/Open-Assistant | 29,137 | Python | notmd | theopfr | Review this pull request change.
Language: TypeScript
File: website/src/pages/team.tsx
PR Title: Updated team page to fit visually more the the rest of the pages, added a button to the call-to-action section which links to the team page.
BEFORE CODE: import Head from "next/head";
import Link from "next/link";
impor... | There is Card and CardBody components 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. |
{enabled && (
<Card>
<CardBody>
<Flex direction="column" gap="2">
<Link href="/chat">
<Button leftIcon={<List />} size="lg">
{t("chat:back_to_chat_list")}
</Button>
</Link>
<ChatConversation... | Maybe we can throw 404 directly here? |
<Card>
<CardBody>
<Flex direction="column" gap="2">
<Link href="/chat">
<Button leftIcon={<List />} size="lg">
{t("chat:back_to_chat_list")}
</Button>
</Link>
<ChatConversation chatId={id} />
</Flex>
... | @@ -32,19 +36,17 @@ const Chat = ({ id }: { id: string }) => {
</Flex>
</CardBody>
</Card>
- </Flags>
+ )}
</>
);
};
Chat.getLayout = getDashboardLayout;
-export const getServerSideProps: GetServerSideProps<{ id: string }, { id: string }> = async ({
- locale = "... | website/src/pages/chat/[id].tsx | 26 | TypeScript | 0.071 | question | 37 | 32 | 36 | false | Added ENABLE_CHAT to chat id page and docker-compose | 2,137 | LAION-AI/Open-Assistant | 29,137 | Python | notmd | yk | Review this pull request change.
Language: TypeScript
File: website/src/pages/chat/[id].tsx
PR Title: Added ENABLE_CHAT to chat id page and docker-compose
BEFORE CODE:
{enabled && (
<Card>
<CardBody>
<Flex direction="column" gap="2">
<Link href="/chat">
... | Maybe we can throw 404 directly 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. |
from oasst_shared.schemas import inference
class ChatRepository(pydantic.BaseModel):
session: database.AsyncSession
class Config:
arbitrary_types_allowed = True
async def get_assistant_message_by_id(self, message_id: str) -> models.DbMessage:
query = (
sqlmodel.select(models.... | name of exception classes in python usually have Error/Exception suffix | from oasst_shared.schemas import inference
class ChatRepository(pydantic.BaseModel):
session: database.AsyncSession
class Config:
arbitrary_types_allowed = True
async def get_assistant_message_by_id(self, message_id: str) -> models.DbMessage:
query = (
sqlmodel.select(models.... | @@ -30,6 +31,9 @@ async def start_work(
logger.debug(f"Starting work on message {message_id}")
message = await self.get_assistant_message_by_id(message_id)
+ if message.state == inference.MessageState.cancelled:
+ raise chat_schema.MessageCancelled(message_id=message_id) | inference/server/oasst_inference_server/chat_repository.py | 26 | Python | 0.357 | suggestion | 71 | 51 | 51 | false | Cancelling pending chat messages of user on submission of a new message | 2,141 | LAION-AI/Open-Assistant | 29,137 | Python | andreaskoepf | yk | Review this pull request change.
Language: Python
File: inference/server/oasst_inference_server/chat_repository.py
PR Title: Cancelling pending chat messages of user on submission of a new message
BEFORE CODE: from oasst_shared.schemas import inference
class ChatRepository(pydantic.BaseModel):
session: databa... | name of exception classes in python usually have Error/Exception suffix | 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
import platform
import random
import uuid
from typing import Annotated, Any, Literal, Union
import psutil
import pydantic
import pynvml
from oasst_shared.shared_settings import shared_settings
INFERENCE_PROTOCOL_VERSION = "1"
DEFAULT_MODEL_LENGTHS = {
"_lorem": 1024,
"OpenAssistan... | We can't offer these LLaMa models now either, right? | import enum
import platform
import random
import uuid
from datetime import datetime
from typing import Annotated, Any, Literal, Union
import psutil
import pydantic
import pynvml
from oasst_shared.shared_settings import shared_settings
INFERENCE_PROTOCOL_VERSION = "1"
DEFAULT_MODEL_LENGTHS = {
"_lorem": 1024,
... | @@ -8,20 +8,15 @@
import psutil
import pydantic
import pynvml
+from oasst_shared.shared_settings import shared_settings
INFERENCE_PROTOCOL_VERSION = "1"
-DEFAULT_MODEL_NAME = "distilgpt2"
DEFAULT_MODEL_LENGTHS = {
"_lorem": 1024,
- "gpt2": 1024,
- "distilgpt2": 1024,
- "OpenAssistant/oasst-sft-1-... | oasst-shared/oasst_shared/schemas/inference.py | 19 | Python | 0.214 | question | 52 | 44 | 44 | false | Added param configs from eval to pass to the frontend | 2,163 | LAION-AI/Open-Assistant | 29,137 | Python | olliestanley | yk | Review this pull request change.
Language: Python
File: oasst-shared/oasst_shared/schemas/inference.py
PR Title: Added param configs from eval to pass to the frontend
BEFORE CODE: import datetime
import enum
import platform
import random
import uuid
from typing import Annotated, Any, Literal, Union
import psutil
i... | We can't offer these LLaMa models now either, 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. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.