Communitygithub.com

kaiwu-coding-skill

Model combinatorial optimization problems as QUBO/Ising using the QBoson Kaiwu SDK (Enterprise/Community), handling constraints, precision, version compatibility, and solution decoding. Suitable for facility location, scheduling, routing, covering, Boolean rules, Max-Cut, mixed discrete-continuous optimization, or fixing Kaiwu modeling/solving APIs. PyTorch energy models and RBM/BM/DBN, QVAE, QDiffusion use a separate kpp-coding-skill.

What is kaiwu-coding-skill?

This skill provides a comprehensive guide for using the Kaiwu SDK (QBoson) to model and solve combinatorial optimization problems via QUBO or Ising formulations. It covers the full workflow: validating the Python environment and installing the correct package (kaiwu for Enterprise, kaiwu-community for Community), modeling constraints as quadratic penalty terms using the provided table of common patterns (e.g., exactly one, at most one, implication, OR, resource capacity), setting appropriate penalty coefficients based on rigorous bounds, and using the correct API for the specific SDK version (Enterprise 1.4.0 vs 1.3.1). It includes a runnable code example showing how to create a `QuboModel`, set an objective with penalties, convert to Ising, solve via `SimulatedAnnealingOptimizer`, decode solutions, and validate feasibility against the original problem constraints. The skill emphasizes critical best practices: always re-check original business constraints on decoded solutions, separate penalty/offset from the true objective, avoid inventing non-existent APIs, tune solver parameters (temperature, iterations, pool size) based on problem scale and time budget, and never claim optimality without proof. It also provides guidance on precision handling, hardware workflow integration, code delivery norms (single responsibility, explicit error handling, controlled solving cost, no dead code), and version-specific import paths. The skill is intended for developers and AI agents building Kaiwu-based solvers for real-world tasks like facility location, scheduling, and routing.

Works with~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/qboson/kaiwu-coding-skill/tree/main

Ask in your favorite AI

Open a new chat with this agent skill pre-loaded.

Documentation

Kaiwu Modeling and Solving

First, confirm the target interpreter, distribution, and version; if the problem is given and the license is installed, use it directly without reinstalling or asking. If not installed, use the target environment's python -m pip install kaiwu (Enterprise) or python -m pip install kaiwu-community (modeling only). Both import as kaiwu. Local Enterprise solving requires an existing license; cloud CIM is used only when requested by the user and credentials are provided. When calling real hardware through this skill, task_name must start with kaiwu_skill, e.g., kaiwu_skill_tsp.

First Ensure Model Equivalence

Distinguish the original business objective, feasible region, and solving energy. Use short formulas to describe variables, objectives, and all constraints; the code should express the same model. If the original objective is maximization, you can negate it to construct a QUBO, but still report values according to the original objective. For problem family identification and variant modeling, refer to the problem catalog as needed.

Original RequirementQuadratic Encoding; P is a positive hard-constraint penalty coefficient
Exactly one / equalityP * (sum(x) - c)**2
At most oneP * sum(x[i]*x[j] for i<j)
Choose a implies choose b / both or neitherP*a*(1-b) / P*(a-b)**2
Two-literal OR: at least one trueP * (1-a)*(1-b); not (a+b-1)**2
Weighted soft ORWeight multiplied by violation indicator; single literal is 1-a, two literals is (1-a)*(1-b)
Integer resource upper bound load <= CP*(load+s-C)**2, non-negative integer slack s covers all 0..C
At least one (multiple variables)P*(sum(x)-1-s)**2, s covers 0..n-1

Boolean literal truth value is x, negative literal is 1-x. The violation indicator for OR is 1 only when all literals are false; don't use 1-sum(literals) (can be negative), nor sum(1-literals)**2 (changes preference). Products of three or more literals are higher-order terms and cannot be directly used as quadratic models; appropriate auxiliary variables and equivalent reduction are needed.

Slack variables can be directly defined as Integer('slack', min_value=0, max_value=C), or encoded using binary weights. For example, upper bound C=5, weights [1,2,2] can exactly represent 0..5; if C=0, do not create a slack bit. Generally, for C>0, take k=C.bit_length()-1, weights [2**j for j in range(k)] + [C-(2**k-1)]. Capacity allows slack; do not use (load-C)**2 as an upper bound constraint.

Penalty coefficients should cover the possible improvement range of the original objective: if the minimum non-zero value of a hard penalty is 1, take P greater than the difference between the upper and lower bounds of the original objective. For weighted soft rules, take P greater than the sum of the weights; for non-negative assignment costs, take P greater than the sum of the per-item cost upper bounds. Overly large coefficients will expand the dynamic range and increase sampling difficulty; the basis must be stated, and infinite P cannot be used to fix incorrect models. Use tighter bounds when provable local repair bounds exist. For example, for non-negative weighted vertex cover, the objective is sum(w[i]*x[i]) and the penalty is P*sum((1-x[u])*(1-x[v])): taking P>max(w) suffices. If weights are non-negative integers, default to P=max(w)+1 directly, without arbitrarily increasing the penalty. Because any uncovered edge can be covered by adding one endpoint, the objective increases by at most max(w), the penalty decreases by at least P, and no new violations are introduced. This only applies to this kind of monotonic covering constraint and cannot be applied to capacity, mutual exclusion, or equality constraints; you must explain that repair does not break other constraints.

Enterprise 1.4.0: Directly Use This API Flow

The following is a runnable example choosing one of three; replace the objective, penalty, and original business validation to handle the actual problem. Do not invent interfaces like kaiwu.seed, QuboModel.add_variable, vartype, or iterations_per_temperature.

import numpy as np
from kaiwu.core import (ndarray, Binary, QuboModel, PenaltyMethodConstraint,
                        qubo_matrix_to_ising_matrix, qubo_model_to_ising_model,
                        get_sol_dict, get_val)
from kaiwu.classical import SimulatedAnnealingOptimizer

x = ndarray(3, 'x', Binary)
original = 3*x[0] + 2*x[1] + 4*x[2]
model = QuboModel()
model.set_objective(original + 10*(x.sum()-1)**2)
model.set_constraint_handler(PenaltyMethodConstraint)  # pass class, not instance
q = model.get_matrix()
h, offset = qubo_matrix_to_ising_matrix(q)  # offset is a constant, not a variable dict
variables = qubo_model_to_ising_model(model).get_variables()
solver = SimulatedAnnealingOptimizer(
    initial_temperature=100, alpha=0.99, cutoff_temperature=0.001,
    iterations_per_t=100, size_limit=32, rand_seed=20261001)
pool = np.asarray(solver.solve(h))
valid = []
for row in pool:
    sol = get_sol_dict(row[:-1]*row[-1], variables)
    bits = [int(round(get_val(x[i], sol))) for i in range(3)]
    if sum(bits) == 1:  # for the actual problem, recalculate all original business constraints here
        valid.append((int(round(get_val(original, sol))), bits))
if not valid:
    raise RuntimeError('No feasible solution among SDK candidates')
cost, decision = min(valid)
print({'bits': decision, 'objective': cost, 'feasible': True})

Verified SA parameters: initial_temperature, alpha, cutoff_temperature, iterations_per_t, size_limit, flag_evolution_history, verbose, rand_seed, process_num. Do not pass seed, time_limit, num_reads. To control runtime, manage it externally in batches; do not fake constructor parameters. The bits in the example are binary decisions, not necessarily equal to the solution field for every task. Output field and numbering conventions follow the current task; when JSON is required, use json.dumps, do not copy the example's print format. For small-to-medium-sized constrained problems, you can increase iterations_per_t or use multiple batches with different rand_seed SDK candidates; record the actual time and respect the user's time limit. The example parameters are a starting point and do not guarantee optimality for every problem.

If penalty coefficients make the Ising matrix amplitude much larger than the example temperature, an initial temperature of 100 may not be enough for exploration. When the task does not fix parameters, you can first take initial_temperature=max(100, 2*np.max(np.abs(h))); for local constrained problems with dozens of variables, you can use iterations_per_t=200, size_limit=128 as a starting point, then judge based on actual candidate quality and time limit. Do not directly reuse the small example's temperature and solution pool size while claiming guaranteed optimality.

For optimization delivery with more than a hundred variables and no fixed sampling parameters in the problem, do not end by running only the small example's low sampling configuration. For example, with quality as the goal and an execution budget of about 40 seconds, a default batch for 128-512 variables with sparse coupling (non-zero proportion below 10%) is iterations_per_t=(200,800,2400), size_limit=128. Keep other parameters consistent, always use the specified seed, and compile the original matrix only once. For more variables, denser matrices, or shorter budgets, start with smaller batches like (200,400,800) and test empirically. After each batch, estimate overhead based on actual time and the iteration count proportion for the next batch, reserving at least 20% margin and 2 seconds for decoding and output. If the next batch is expected to finish within the remaining time, continue with the default batch; still judge whether to continue based on candidate quality and time limit below. If it is expected to exceed the time limit, return the best feasible candidate found so far immediately; do not overshoot to finish a fixed number of batches. Maintain only one unified deadline for the entire program. Within the user's execution time limit, recalculate the original business objective for all returned candidates and retain the feasible candidate with the lowest cost; this is a solving strategy with a budget within the program. Do not take the first feasible candidate as the best result. Soft preferences are not hard constraints: without hard constraints, do not introduce large penalty coefficients artificially, nor add balance restrictions not required by the problem.

Adjust default parameters according to scale and complexity. The above numerical values are empirical starting points, not a fixed recipe for all problems. First consider the number of variables, number of non-zero couplings, coefficient range, and hard constraint strength, then arrange the batch size in combination with the execution time limit. Dense matrices or many auxiliary variables increase the per-solve overhead; first test with small batches, reserving time for compilation, decoding, and output. Increasing iterations, slowing down cooling, or expanding the solution pool does not guarantee better business results; cumulatively retain the best feasible SDK candidate found so far, compare the feasible ratio, original business cost, and actual time to decide whether to continue; do not overwrite better old candidates. Prioritize correcting incorrect modeling or overly large penalty coefficients before tuning parameters; record the parameters used and the stopping condition, and never claim guaranteed optimality.

First obey the experimental parameters specified by the task. If the problem fixes the random seed, each time you create a solver, explicitly use the same designated rand_seed; do not increment, create a list of seeds, or generate seeds from time; the multiple-seed suggestion above is only for scenarios where the task allows it. With a fixed seed, only adjust temperature, iteration count and other parameters if the problem allows; record the real configuration.

solve returns a spin pool not sorted by energy; the last column is the reference spin. Iterate over each row, first normalize by multiplying by the reference spin, then decode using the variable dictionary of the Ising model. Use get_val to access variables; do not guess internal string keys. Only decisions decoded from actual candidates and verified by the original problem can be output; do not use enumeration, hardcoded answers, or third-party solvers to replace the SDK.

Penalty terms added to the objective are not equivalent to registered constraints: without add_constraint, verify_constraint returning 0 does not prove the original problem is feasible. Regardless of registration, recalculate all business constraints from the decision. If you call verify_constraint, first unpack unsatisfied, details = model.verify_constraint(sol). Business cost and QUBO/Ising energy should be printed separately; do not treat penalty terms, constant offsets, or maximization negation signs as business metrics. When handing off coefficients, save variable order, constants, linear terms, quadratic terms, and auxiliary variable mappings; P is actually multiplied into coefficients, and each contribution is accumulated. The SDK matrix order may not equal the array creation order; the converter offset does not include business constants removed during expression compilation, so save them separately. Cost for same state is w*(1-x[i]-x[j]+2*x[i]*x[j]), cost for different state is w*(x[i]+x[j]-2*x[i]*x[j]); verify the direction with 00, 01, 10, 11 to avoid confusing co-channel interference with Max-Cut objective.

The reporting format for weighted soft rules follows the problem: if the requirement is "minimize violation cost", report sum(weight for rule in soft if not satisfied(rule)), and select the candidate with the smallest such value. "Sum of satisfied weights" and "violation cost" sum to the total soft weight; their optimization directions are opposite, and the field name 'objective' cannot be mixed. Before output, recalculate the original objective based on the final bits; even if the decision is the same, reporting a value with the opposite format is a delivery error.

Version and Thematic References: Only Read Relevant Parts

APIEnterprise 1.3.1Enterprise 1.4.0
QuboModelkaiwu.qubokaiwu.core
Two QUBO/Ising converterskaiwu.conversionkaiwu.core
ndarray/Binary/Integer/quicksum/get_val/get_sol_dict/PenaltyMethodConstraintkaiwu.corekaiwu.core
Array value accesselement-wise get_val or get_array_valget_val supports arrays; no get_array_val
PrecisionReducerkaiwu.cimkaiwu.preprocess
Penalty method solverkaiwu.solver.PenaltyMethodSolverkaiwu.hybrid.PenaltyMethodOptimizer

When the version is known, import the corresponding module directly. When cross-version is explicitly required or cannot be confirmed, only make compatibility branches for the actual migrated imports. quicksum accepts a list across versions; ndarray((n,m), 'x', Binary) uses positional arguments. Community cannot assume a local classical solver.

  • 1.3.x or more complete signatures: Enterprise API, API Overview.
  • 1.3.x TSP historical example: SDK Examples; migrating to 1.4.x must change imports according to the table above.
  • Precision handling: PrecisionReducer is an optimizer decorator; default values change between versions, explicitly pass only_feasible_solution; perform_precision_adaption_split returns (split_matrix, last_var_idx); restore and verify the original matrix energy according to the mapping.
  • Hardware integration: Workflow Supplement, read only when the task requires real hardware.
  • Other interfaces: Module Index, Community.
  • Problems with both continuous and discrete decisions: first write the complete coupling constraints; Kaiwu solves for discrete candidates, then fix the discrete variables and resolve with continuous/subproblem decisions. Do not binary-expand large numbers of continuous variables as a whole; do not remove coupling constraints like "if not enabled, flow is zero".

Delivery and Verification

When generating from scratch, provide a complete script; when modifying existing code, provide only the necessary changes. Comply with the problem data, output protocol, and time limit; prioritize code completeness. When execution conditions permit, first check imports, then actually compile, solve, decode, and verify the original business; if execution is prohibited by the task, do not claim it was run.

Mathematical self-check focuses on two points: for every feasible business state, can auxiliary variables be chosen so that the hard penalty term is zero? Is the energy then equal to the original objective plus a constant? In independent development verification, you can use truth tables or small instance enumeration to check for encoding errors, but do not mix such enumeration results with SDK return results. Only claim optimality if you have a reference bound or independent proof; otherwise, report the feasible solution found, the actual objective value, and the limitation that optimality is not proven.

Supplementary: Code Delivery Standards

The following rules constrain newly added and modified SDK code; keep the modeling and version requirements above.

  • Maintain single responsibility. Organize modeling, SDK solving, candidate decoding, and original business verification into clear steps; for small scale, one script and a few functions suffice. Do not introduce generic frameworks, plugin registration, multiple inheritance, or extensive forwarding wrappers just to call the SDK once. Remove dead code, duplicate branches, and unused dependencies generated by this change.
  • Use confirmed interfaces. When the SDK version is known, import the corresponding API directly; do not scan the entire package or try guessing class names and parameters in turn. If compatibility with existing multiple versions is truly needed, write narrow branches only around the actually migrated interfaces; do not disguise business errors as version compatibility issues.
  • Exceptions must have clear handling results. Only catch specific exceptions you can handle at real boundaries like input, authorization, or external calls; if unrecoverable, keep the reason and exit with failure. Prohibit except Exception: pass, multiple repeated catches, infinite retries, and returning fake feasible solutions or "success" defaults after errors. Do not add meaningless try/except for fixed internal calculations.
  • Validate at real boundaries. Check required dimensions, value ranges, and constraint consistency for external data; for internally validated data, do not repeatedly check layer by layer, and do not attach a security framework unrelated to the task for a local small script. Read secrets from existing environment or configuration; do not hardcode or write to logs; do not use eval, exec, or concatenated shell commands to parse data. Installation, networking, and cloud submissions must comply with the authorization scope of the current task.
  • Keep solving cost controllable. Set temperature decay, iterations per temperature, and pool size according to variable scale and time limit; avoid starting with extremely large parameters. The outer loop cannot interrupt a blocking solve call, so a single batch must be small enough; manage batches using a monotonic clock and record actual time. Stop when the call count, time, or cost limit is reached; do not delay by repeated reconnection.
  • Reduce ineffective computation. Reuse unchanged matrices, data, and variable mappings; decode and filter candidates batch by batch; do not accumulate duplicate solutions unboundedly; do not replace clear calculations with huge intermediate arrays. Do not delete real constraints, change the original objective, or replace solving results with non-SDK answers for speed.
  • Make indices and units explicit. Unify input numbering and array subscripts at the entry point; for positive/negative literals, use idx = abs(literal) - 1 to locate, then decide whether to invert. Distinguish the business objective, penalty terms, and energy offset; use variable names that clearly indicate meaning, and do not write a set of contradictory conversions across multiple functions.
  • Only perform verifications that can justify correctness. Check representative feasible/infeasible boundaries, the original business objective, and the actual SDK candidate source; do not treat tests that only match the implementation text as proof. Deliver complete, runnable necessary code; explicitly state what has been actually verified; if it cannot be run, state so directly; do not fake execution records.

Related Skills