@@ -495,6 +495,8 @@ class StableDiffusionGGML {
495495
496496 std::shared_ptr<RNG> rng = std::make_shared<PhiloxRNG>();
497497 std::shared_ptr<RNG> sampler_rng = nullptr ;
498+ std::minstd_rand fallback_rng;
499+
498500 int n_threads = -1 ;
499501 float default_flow_shift = INFINITY;
500502
@@ -618,6 +620,8 @@ class StableDiffusionGGML {
618620
619621 bool use_tae = false ;
620622
623+ fallback_rng.seed (std::chrono::system_clock::now ().time_since_epoch ().count ());
624+
621625 rng = get_rng (sd_ctx_params->rng_type );
622626 if (sd_ctx_params->sampler_rng_type != RNG_TYPE_COUNT && sd_ctx_params->sampler_rng_type != sd_ctx_params->rng_type ) {
623627 sampler_rng = get_rng (sd_ctx_params->sampler_rng_type );
@@ -2461,6 +2465,17 @@ class StableDiffusionGGML {
24612465 flow_denoiser->set_shift (flow_shift);
24622466 }
24632467 }
2468+
2469+ int64_t get_seed (int64_t seed) {
2470+ if (seed < 0 ) {
2471+ // prevent potential issues if 'stable-diffusion.cpp' is invoked
2472+ // as a library by a third party with a seed <0
2473+ seed = fallback_rng ();
2474+ LOG_DEBUG (" generated %" PRId64 " as random seed" , seed);
2475+ }
2476+ return seed;
2477+ }
2478+
24642479};
24652480
24662481/* ================================================= SD API ==================================================*/
@@ -2990,13 +3005,6 @@ sd_image_t* generate_image_internal(sd_ctx_t* sd_ctx,
29903005 ggml_tensor* concat_latent = nullptr ,
29913006 ggml_tensor* denoise_mask = nullptr ,
29923007 const sd_cache_params_t * cache_params = nullptr ) {
2993- if (seed < 0 ) {
2994- // Generally, when using the provided command line, the seed is always >0.
2995- // However, to prevent potential issues if 'stable-diffusion.cpp' is invoked as a library
2996- // by a third party with a seed <0, let's incorporate randomization here.
2997- srand ((int )time (nullptr ));
2998- seed = rand ();
2999- }
30003008
30013009 if (!std::isfinite (guidance.img_cfg )) {
30023010 guidance.img_cfg = guidance.txt_cfg ;
@@ -3312,11 +3320,7 @@ sd_image_t* generate_image(sd_ctx_t* sd_ctx, const sd_img_gen_params_t* sd_img_g
33123320 return nullptr ;
33133321 }
33143322
3315- int64_t seed = sd_img_gen_params->seed ;
3316- if (seed < 0 ) {
3317- srand ((int )time (nullptr ));
3318- seed = rand ();
3319- }
3323+ int64_t seed = sd_ctx->sd ->get_seed (sd_img_gen_params->seed );
33203324 sd_ctx->sd ->rng ->manual_seed (seed);
33213325 sd_ctx->sd ->sampler_rng ->manual_seed (seed);
33223326
@@ -3672,11 +3676,7 @@ SD_API sd_image_t* generate_video(sd_ctx_t* sd_ctx, const sd_vid_gen_params_t* s
36723676 return nullptr ;
36733677 }
36743678
3675- int64_t seed = sd_vid_gen_params->seed ;
3676- if (seed < 0 ) {
3677- seed = (int )time (nullptr );
3678- }
3679-
3679+ int64_t seed = sd_ctx->sd ->get_seed (sd_vid_gen_params->seed );
36803680 sd_ctx->sd ->rng ->manual_seed (seed);
36813681 sd_ctx->sd ->sampler_rng ->manual_seed (seed);
36823682
0 commit comments